LeetCode-32.Longest Valid Parentheses

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

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.

public int LongestValidParentheses(string s) 
    {
        int start=0,max = 0;
        Stack<int> stack = new Stack<int>(); 
        for (int i = 0; i < s.Length; i++)
        {
            if(s[i]==')')
            {
                if (stack.Count == 0)
                    start=i+1;
                else
                {
                    stack.Pop();
                    if (stack.Count == 0)
                        max = Math.Max(max, i - start + 1);
                    else
                        max = Math.Max(max, i - stack.Peek());
                }    

            }
            else
            {
                stack.Push(i);
            }
        }
        return max;
    }
参考: http://blog.csdn.net/linhuanmars/article/details/20439613

你可能感兴趣的:(LeetCode)