leetcode----最长有效括号字串

题目描述


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.


class Solution {
public:
    int longestValidParentheses(string s) {
        stack<int> ss;
        int max = 0;
        //1、通过记录匹配括号的位置信息,来确认当前有效字串的最大长度
        //(由于记录了更多信息,所以能力更强)
        //2、当栈为空时,表示匹配至此处的整个字符串有效。
        int t;
        for( int i= 0; i< s.size() ; i++){
            if( s[i] == ')' && !ss.empty() && s[ss.top()] == '('){
                ss.pop();
                if( ss.empty())
                    max = i+1;
                else
                    //记录当前子串有效长度
                    if( i - ss.top() > max)
                        max = i - ss.top();
            }
            else
                ss.push(i);
        }
        return max;
    }
};


你可能感兴趣的:(LeetCode,C++)