1. 程式人生 > >LeetCode-32. 最長有效括號

LeetCode-32. 最長有效括號

題目地址:https://leetcode-cn.com/problems/longest-valid-parentheses/
思路:預處理所有匹配成功的括號,然後問題轉化為最長連續子序列。
AC程式碼:

class Solution {
public:
    int longestValidParentheses(string s) {
        int length = s.length();
        stack<int>k;
        bool flag[100005];
        memset(flag,false,sizeof(flag));
        int ans = 0;
        int count = 0;
        for(int i=0;i<length;i++){
            if(s[i] == '(')
                k.push(i);
            else{
                if(!k.empty()){
                    int now = k.top();
                    k.pop();
                    flag[now] = true;
                    flag[i] = true;
                }
            }
        }
        for(int i = 0;i<length;i++){
            if(flag[i])
                count++;
            else{
                ans = max(ans,count);
                count = 0;
            }
        }
        ans = max(ans,count);
        return ans;
    }
};