two C++ solution, DP & stack


  • 0
    class Solution {
    public:
        int longestValidParentheses(string s) {
            vector<int> dp(s.size() + 1, 0);
            int ans = 0;
            for (int i = 0; i < s.size(); ++i) {
                if (s[i] == '(') continue;
                int start = i - dp[i] - 1;
                if (start >= 0 && s[start] == '(')
                    dp[i + 1] = dp[i] + 2 + dp[start];
                ans = max(ans, dp[i + 1]);
            }
            return ans;
        }
    };
    
    class Solution {
    public:
        int longestValidParentheses(string s) {
            stack<int> st;
            st.push(-1);
            int ans = 0;
            for (int i = 0; i < s.size(); ++i) {
                if (s[i] == ')' && st.top() != -1 && s[st.top()] == '(') st.pop();
                else st.push(i);
                ans = max(ans, i - st.top());
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.