-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32.cpp
More file actions
83 lines (72 loc) · 1.75 KB
/
32.cpp
File metadata and controls
83 lines (72 loc) · 1.75 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/**
* 32. Longest Valid Parentheses
* Given a string containing just the characters '(' and ')', return the length
* of the longest valid (well-formed) parentheses substring.
*/
#include <iostream>
#include <vector>
using namespace std;
/**
* dynamic programming
*
* defination
* dp[i] indicates the longest legnth of valid parentheses substring that ends
* with s[i]
*
* initialization
*
* state transition
* if s[i] is ')'
* if s[i-1] is '(' then dp[i] = dp[i-2]+2.
* dp[i-2] is the longest length of valid substring before s[i] and
* s[i-1]. +2 is the length of "()"
*
* dp[i] = dp[i-1] + dp[i-dp[i-1]-2] + 2
*
* if s[i] is '(' then dp[i] is 0.
*/
int longestValidParentheses(string s) {
if (s.empty()) {
return 0;
}
const int n = s.size();
vector<int> dp(n, 0);
int ret = 0;
for (int i = 1; i < n; ++i) {
if (s[i] == '(') {
continue;
}
// s[i] == ')'
if (s[i - 1] == '(') {
dp[i] = (i >= 2 ? dp[i - 2] : 0)+ 2;
} else {
if (i - 1 - dp[i - 1] >= 0 && s[i - 1 - dp[i - 1]] == '(') {
dp[i] = dp[i - 1] +
(i - dp[i - 1] - 2 >=0 ?
dp[i - dp[i - 1] - 2] :
0) + 2;
}
}
ret = max(ret, dp[i]);
}
return ret;
}
void test() {
string s;
int ret;
cout << "s:" << s << endl;
ret = longestValidParentheses(s);
cout << ret << endl;
s = "(()";
cout << "s:" << s << endl;
ret = longestValidParentheses(s);
cout << ret << endl;
s = ")()())";
cout << "s:" << s << endl;
ret = longestValidParentheses(s);
cout << ret << endl;
}
int main() {
test();
return 0;
}