-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-valid-parentheses.cc
44 lines (41 loc) · 1.21 KB
/
longest-valid-parentheses.cc
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
#include "leetcode.h"
using namespace std;
class Solution {
public:
int longestValidParentheses(const string &str) {
int max_len = 0, idx = 0;
while (idx < str.length()) {
if (str[idx] == ')') {
++idx;
continue;
}
for (size_t i = 0, flag = 0; idx < str.length() && flag >= 0; ++i, ++idx) {
if (str[idx] == '(') {
++flag;
} else {
--flag;
}
if (flag == 0) { max_len = std::max(max_len, static_cast<int>(i + 1)); }
}
}
idx = str.length() - 1;
while (idx >= 0) {
if (str[idx] == '(') {
--idx;
continue;
}
for (auto i = 0, flag = 0; idx >= 0 && flag >= 0; ++i, --idx) {
if (str[idx] == ')')
++flag;
else
--flag;
if (flag == 0) max_len = std::max(max_len, i + 1);
}
}
return max_len;
}
};
int main(int argc, char const *argv[]) {
Solution solution;
cout << solution.longestValidParentheses("((()()(()((()") << endl;
}