LeetCode实战:最长有效括号

题目英文

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

<b>Example 1</b>:

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

<b>Example 2</b>:

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

题目中文

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

<b>示例 1</b>:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"

<b>示例 2</b>:

输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"

<b>示例 3</b>:

输入: ""
输出: 0
解释: 

<b>示例 4</b>:

输入: "()(())"
输出: 6
解释: 最长有效括号子串为 "()(())"

算法实现

我们可以用栈在遍历给定字符串的过程中去判断到目前为止扫描的子字符串的有效性,同时计算最长有效字符串的长度。我们首先将 −1 放入栈顶。

  • 对于遇到的每个‘(’,我们将它的下标放入栈中。
  • 对于遇到的每个‘)’,我们弹出栈顶的元素,判断有效性,计算有效长度。
public class Solution {
    public int LongestValidParentheses(string s) {
        Stack<int> stack = new Stack<int>();
        stack.Push(-1);
        int result = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] == '(')
            {
                stack.Push(i);
            }
            else
            {
                stack.Pop();
                if (stack.Count == 0)
                {
                    stack.Push(i);
                }
                else
                {
                    result = Math.Max(result, i - stack.First());
                }
            }
        }
        return result;
    }
}

实验结果

  • 状态:通过
  • 230 / 230 个通过测试用例
  • 执行用时:104 ms
提交结果

相关图文

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容