leetcode 32. Longest Valid Parentheses

link

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.

 题意:

我又读题渣渣了。 题意上在给定的string s 上,找到一个合法的子串,该子串是一个合法的括号序列。

思路:

当遇到)时我们要去匹配(,匹配(的问题一般交给栈来解决。 

维护一个栈st, 保存所有可用的 ( 的下标。 

维护一个数preRight,表示上一次st清空的位置。

如上述,遇到 ( 的时候无脑push。

当遇到):

  若栈为空,则以该串及其左边为起始肯定是不合法的。 【否则匹配到这个)的时候会遇到没有(可以用的问题】。 因此清空stack, 记录目前的下标为preRight。

  若栈不为空, 则可以匹配栈顶的(, pop掉这个(后,

    若栈非空,则以此)结尾的子串的合法起始位置是st.top() + 1, e.g. )( , (()),红色为起始位置,蓝色为top,灰底为枚举的)。 ans = max(ans, i - (st.top() + 1) + 1);

    若栈为空,则就要用到之前preRight的位置了。 ans = max(ans, i - preRight); 

CODE:

class Solution {
public:
    int longestValidParentheses(string s) {
        int ans = 0, tmp = 0;
        stack<int> st;
        int preRight = -1;
        for(int i = 0; i < s.length(); i++ ){
            if(s[i] == '(') {
                st.push(i);
            }
            else{
                if(st.empty()) {
                    preRight = i;
                    while(!st.empty()) st.pop();
                }else{
                    st.pop();
                    if(st.empty()){
                        ans = max(ans, i - preRight);
                    }else{
                        ans = max(ans, i - st.top());
                    }
                }
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/bbbbbq/p/7622417.html