forked from illuz/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AC_simulation_n.cpp
61 lines (53 loc) · 1.33 KB
/
AC_simulation_n.cpp
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
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_simulation_n.cpp
* Create Date: 2015-01-26 10:45:35
* Descripton: Use O(1) space and O(n) time
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
class Solution {
public:
int longestValidParentheses(string s) {
int max_len = 0, depth = 0, start = -1;
// solve ((()
for (int i = 0; i < s.size(); ++i) {
if (s[i] == '(')
++depth;
else {
--depth;
if (depth == 0)
max_len = max(max_len, i - start);
else if (depth < 0) {
start = i;
depth = 0;
}
}
}
// solve ()))
depth = 0;
start = s.size();
for (int i = s.size(); i >= 0; --i) {
if (s[i] == ')')
++depth;
else {
--depth;
if (depth == 0)
max_len = max(max_len, start - i);
else if (depth < 0) {
start = i;
depth = 0;
}
}
}
return max_len;
}
};
int main() {
string test;
Solution s;
while (cin >> test)
cout << s.longestValidParentheses(test) << endl;
return 0;
}