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 class Solution {
    public int longestValidParentheses(String s) {
        int maxLen = 0;
        Stack<Integer> stack = new Stack<Integer>();
        int left = 0;
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i) == '(')
               stack.push(i);
            else
            {            
                if(stack.empty())
                   left = i+1;  //记录起始位置的下标
                else
                {
                    stack.pop();
                    if(stack.empty())
                      maxLen = Math.max(maxLen,i-left+1);
                    else
                      maxLen = Math.max(maxLen,i-stack.peek());
                }
            }
        }
        return maxLen;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容