leetcode-----32. 最长有效括号

思路

将整个序列分段,即刚刚不满足左括号数量大于等于右括号数量条件的情况;则任何一个合法序列在每个段内。
使用栈来存储位置。

代码

class Solution {
public:
    int longestValidParentheses(string s) {
        int n = s.size(), ans = 0;
        stack<int> stk;

        for (int i = 0, start = -1; i < n; ++i) {
            if (s[i] == '(') stk.push(i);
            else {
                if (stk.size()) {
                    stk.pop();
                    if (stk.size()) {
                        ans = max(ans, i - stk.top());
                    } else {
                        ans = max(ans, i - start);
                    }
                } else {
                    start = i;
                }
            }
        }
        return ans;
    }
};

猜你喜欢

转载自www.cnblogs.com/clown9804/p/13193169.html