-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParentheses.cc
More file actions
32 lines (29 loc) · 986 Bytes
/
LongestValidParentheses.cc
File metadata and controls
32 lines (29 loc) · 986 Bytes
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
namespace LongestValidParentheses {
class Solution {
public:
int longestValidParentheses(string s) {
int max = 0;
stack<int> st;
int lastInvalidRightParentheses = -1; // assume there is a "hidden" invalid ")" before the start of string
int i = 0;
while (i < s.size()) {
char c = s[i];
if (c == '(') {
st.push(i);
} else { // ')'
if (!st.empty()) {
st.pop();
int start = st.empty()? lastInvalidRightParentheses: st.top();
if (i - start > max) {
max = i - start;
}
} else {
lastInvalidRightParentheses = i;
}
}
i++;
}
return max;
}
};
}