forked from pengsida/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode32.cpp
45 lines (43 loc) · 1.14 KB
/
leetcode32.cpp
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
42
43
44
45
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
vector<int> rec;
int ans = 0;
int nr_left = 0;
for (auto w : s) {
if (w == '(') {
rec.push_back(-1);
nr_left++;
continue;
}
nr_left--;
if (nr_left < 0) {
rec.clear();
nr_left = 0;
continue;
}
if (rec.back() == -1) {
rec.pop_back();
if (rec.empty() || rec.back() == -1)
rec.push_back(2);
else
rec.back() = rec.back() + 2;
} else {
int tmp = rec.back() + 2;
rec.pop_back();
rec.pop_back();
if (rec.empty() || rec.back() == -1)
rec.push_back(tmp);
else
rec.back() = rec.back() + tmp;
}
if (rec.back() > ans)
ans = rec.back();
}
return ans;
}
};