forked from cpselvis/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution032.cpp
More file actions
57 lines (51 loc) · 779 Bytes
/
solution032.cpp
File metadata and controls
57 lines (51 loc) · 779 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
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
/**
* Longest Valid Parentheses
* stack
*
* cpselvis([email protected])
* September 11th, 2016
*/
#include<iostream>
#include<stack>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
int ret = 0;
int left = -1;
for (int i = 0; i < s.size(); i ++)
{
if (s[i] == '(')
{
st.push(i);
}
else
{
if (st.empty())
{
left = i;
}
else
{
st.pop();
if (st.empty())
{
ret = max(ret, i - left);
}
else
{
ret = max(ret, i - st.top());
}
}
}
}
return ret;
}
};
int main(int argc, char **argv)
{
Solution s;
cout << s.longestValidParentheses(")()())") << endl;
cout << s.longestValidParentheses("()(())") << endl;
}