Longest Valid Parentheses

来源:互联网 发布:tab切换代码原声js 编辑:程序博客网 时间:2024/04/29 17:30
   public int longestValidParentheses(String s) {        // Start typing your Java solution below        // DO NOT write main() function        if(s == null || s.length() == 0) return 0;        int result = 0;        int left = -1;//pay attention here, left means the impossible left side        Stack<Integer> stack = new Stack<Integer>();        for(int i = 0; i < s.length(); i++) {            if(s.charAt(i) == '(') stack.push(i);            else {                if(stack.empty()) left = i;                else {                    stack.pop();                    if(stack.empty()) result = Math.max(result, i - left);                    else result = Math.max(result, i - stack.peek());                }            }        }        return result;    }