aboutsummaryrefslogtreecommitdiff
path: root/longest_valid_parentheses.cpp
blob: 953e8be31e926a56cb3df93580a9e84240a1ce20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "leetcode.h"

class Solution {
public:
  int longestValidParentheses(string s) {
    int n = s.size(), ans = 0;
    stack<int> stk;
    for (int i = 0; i < n; i++) {
      if (s[i] == '(')
        stk.push(i);
      else {
        if (!stk.empty()) {
          if (s[stk.top()] == '(')
            stk.pop();
          else
            stk.push(i);
        } else
          stk.push(i);
      }
    }
    if (stk.empty())
      ans = n;
    else {
      int a = n, b = 0;
      while (!stk.empty()) {
        b = stk.top();
        stk.pop();
        ans = max(ans, a - b - 1);
        a = b;
      }
      ans = max(ans, a);
    }
    return ans;
  }
};

int main() {
  Solution obj;
  string s = ")()())";
  cout << obj.longestValidParentheses(s);
}