LeetCode实战:最长有效括号

2019-08-16  本文已影响0人  老马的程序人生

题目英文

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;
    }
}

实验结果

提交结果

相关图文

上一篇 下一篇

猜你喜欢

热点阅读