forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestValidParentheses.cpp
More file actions
36 lines (33 loc) · 962 Bytes
/
longestValidParentheses.cpp
File metadata and controls
36 lines (33 loc) · 962 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
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length();
if (n <= 1) return 0;
int ret = 0;
vector<int> mm(n, 0);
RFOR(i,n-2,0) {
if (s[i] == ')') continue;
int rt = i + mm[i + 1] + 1;
if (rt < n && s[rt] == ')') {
mm[i] = mm[i + 1] + 2;
if (++rt < n) mm[i] += mm[rt];
}
ret = max(ret, mm[i]);
}
return ret;
}
};
int main() {
Solution s;
cout << s.longestValidParentheses("(()") << endl;
cout << s.longestValidParentheses(")()())") << endl;
cout << s.longestValidParentheses("(((()(()") << endl;
return 0;
}