My O(N) C++ solution easy to understand


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

Log in to reply
 

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