leetcode--LongestValidParentheses

来源:互联网 发布:linux怎么退出编辑模式 编辑:程序博客网 时间:2024/04/30 01:08

思路:

遍历s,遇到‘(’入栈,遇到‘)’且栈顶为‘(’将栈顶出栈并计算长度。length=i-stack.peek()这样可以将所有规范的长度计算出来。而遇到‘)’且栈顶不是‘(’说明0-i已经不能再形成规范的字符串,将i入栈,与之后的计算隔离。

public int longestValidParentheses(String s) {        Stack<Integer>stack=new Stack<Integer>();        stack.push(-1);        int max=0;        for(int i=0;i<s.length();i++){            if(s.charAt(i)=='(')stack.push(i);            else if(stack.peek()!=-1){                if(s.charAt(stack.peek())=='('){                    stack.pop();                    int length=i-stack.peek();                    max=(max<length)?length:max;                }else{                    stack.push(i);                }            }else{                stack.push(i);            }        }        return max;    }


0 0