My DP solution without using stack


  • 0
    L
    class Solution {
    public:
        int longestValidParentheses(string s) {
            if (s.length() == 0) return 0;
            int dp[s.length()]{0};
            dp[0] = 0, dp[1] = (s[0] == '(' && s[1] == ')') ? 2 : 0;
            int max = dp[1];
            for (int i = 2; i < s.length(); i ++) {
                if (s[i] == '(') dp[i] = 0;
                else {
                    if (s[i - 1] == '(') dp[i] = dp[i - 2] + 2;
                    else if (i - 1 - dp[i - 1] >= 0 && s[i - 1 - dp[i - 1]] == '(') {
                        dp[i] = dp[i - 1] + 2;
                        if (i - 2 - dp[i - 1] >= 0) dp[i] += dp[i - 2 - dp[i - 1]];
                    }
                    else dp[i] = 0;
                }
                max = max > dp[i] ? max : dp[i];
            }
            return max;
        }
    };

Log in to reply
 

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