LeetCode 121 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.

分析:

括号匹配问题,用到栈。


用栈存左括号下标,

碰见右括号时,

如果栈为空,则当前右括号不合法,则start需要更新,start从下一个位置开始,(这样重复往后,一定会找到一个合法开始);

如果栈不为空,则弹栈并计算max。

public class Solution {
    public int longestValidParentheses(String s) {
        int max = 0;
        int start=0;//有效下标的开始
        Stack<Integer> st = new Stack<Integer>();
        for(int i=0; i<s.length(); i++){
            if(s.charAt(i)=='(')
                st.push(i);//左括号入栈
            else{//碰见右括号
                if(st.empty())//空栈,当前右括号不合法,start从下一个位置开始
                    start = i+1;
                else{
                    st.pop();
                    if(st.empty())//计算有效括号长度
                        max = Math.max(max, i-start+1);
                    else
                        max = Math.max(max, i-st.peek());
                }
                
            }
        }
        return max;
    }
}


你可能感兴趣的:(LeetCode,valid,parent,longest)