-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParentheses.cpp
More file actions
37 lines (34 loc) · 1.01 KB
/
LongestValidParentheses.cpp
File metadata and controls
37 lines (34 loc) · 1.01 KB
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
/**
Given a string containing just the characters '(' and ')', find the length of the
longest valid (well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()",
which has length = 4.
*/
class Solution {
public:
int longestValidParentheses(string s) {
int maxLen = 0;
int last = -1;
stack<int> st;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(') {
st.push(i);
}
else {
if (st.empty()) {
last = i;
}
else {
st.pop();
if (st.empty()) {
maxLen = std::max(maxLen, i - last);
}else {
maxLen = std::max(maxLen, i - st.top());
}
}
}
}
return maxLen;
}
};