[LeetCode] 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.

class Solution {
public:
    int ans = 0;
    int longestValidParentheses(string s) {
        bool *a = new bool[s.length()];
        memset(a,false,s.length());
        stack<int> st;
        for(int i = 0;i < s.length();i ++){
            if(s[i] == '(')
                st.push(i);
            else if(s[i] == ')' && !st.empty()){
                a[i] = true;
                a[st.top()] = true;
                st.pop();
            }
        }
        int cur_len = 0;
        for(int i = 0;i < s.length();i ++){
            if(a[i]) cur_len ++;
            else cur_len = 0;
            ans = max(ans,cur_len);
        }
        return ans;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章