C++ O(N) time with stack, easy to understand


  • 2
    S
    class Solution {
    public:
        int longestValidParentheses(string s) {
            if(s.empty())   return 0;
            stack<int> stk;
            for(int i=0;i<s.size();i++){
                if(s[i] == '(') stk.push(i);
                else{
                    if(stk.empty()) continue;
                    int k = stk.top();
                    stk.pop();
                    s[k] = '*';
                    s[i] = '*';
                }
            }
            int maxLen = 0,i = 0,j = 0, N = s.size();
            while(i<N){
                while(i<N && s[i] != '*')   i++; 
                j = i;
                while(j<N && s[j] == '*')   j++;
                maxLen = max(maxLen,j-i);
                i = j;
            }
            return maxLen;
        }
    };
    

Log in to reply
 

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