o(n) simple solution using stack of C++


  • 0
    H
    class Solution {
    public:
        int longestValidParentheses(string s) {
            int max = 0;
            stack<int> idx;
    
            int len = 0;
            for (int i = 0; i < s.size(); ++i){
                if (s[i] == '('){
                    idx.push(i - len);
                    len = 0;
                }else if (s[i] == ')'){
                    if (idx.empty()){
                        len = 0;
                    }else{
                        len = i - idx.top() + 1;
                        max = max > len? max:len;
                        idx.pop();
                    }
                }
            }
            return max;    
        }
    };
    

Log in to reply
 

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