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
|
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
st.push(-1);
int max = 0;
int i = 0;
while(i < s.length()) {
int top = st.top();
if(top == -1) {
st.push(i);
}
else {
if(s[top] == '(' && s[i] == ')') {
st.pop();
}
else {
st.push(i);
}
}
i++;
}
int now = s.length();
while(!st.empty()) {
int before = st.top();
st.pop();
if((now - 1 - before) % 2 == 0 && now - 1 - before > max)
max = now - 1 - before;
now = before;
}
return max;
}
};
|