-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestValidParentheses.cc
76 lines (56 loc) · 1.29 KB
/
LongestValidParentheses.cc
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <vector>
#include <string>
#include <iostream>
using std::vector;
using std::string;
using std::cout;
using std::endl;
#include <cstdlib>
using std::atoi;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(NULL){}
};
#include <algorithm>
#include <cstring>
#include <stack>
class Solution{
public:
int longestValidParentheses(string s){
std::stack<std::pair<char,int> > st;
int ans = 0;
vector<int> dp(s.length() + 10, 0);
dp[0] = 0;
int pos = 1;
for(auto &c: s){
if('(' == c){
st.push({c, pos});
dp[pos] = 0;
}else{
if(!st.empty()){
auto p = st.top();
if('(' == p.first){
dp[pos] = dp[p.second - 1] + pos - p.second + 1;
}else{
dp[pos] = 0;
}
st.pop();
}else{
dp[pos] = 0;
}
}
ans = std::max(ans, dp[pos++]);
}
return ans;
}
};
int main(){
Solution slu;
using std::cin;
string s;
while(cin >> s){
cout << slu.longestValidParentheses(s) << endl;
}
return 0;
}