-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-valid-parentheses.cc
54 lines (46 loc) · 1.03 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
45
46
47
48
49
50
51
52
53
54
// https://oj.leetcode.com/problems/longest-valid-parentheses/
#include <string>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
int longestValidParentheses(string s) {
#if 1
// http://fisherlei.blogspot.com/2013/03/leetcode-longest-valid-parentheses.html
stack<int> stk;
int longest = 0;
for (string::size_type i = 0; i < s.size(); i++) {
if (s[i] == '(' || stk.empty() || s[stk.top()] == ')') {
stk.push(i);
} else {
stk.pop();
int len = stk.empty() ? i + 1 : i - stk.top();
longest = max(longest, len);
}
}
return longest;
#else
vector<int> dp(s.size() + 1);
stack<int> stk;
int longest = 0;
for (string::size_type i = 0; i < s.size(); i++) {
if (s[i] == '(' || stk.empty() || s[stk.top()] == ')') {
dp[i] = 0;
stk.push(i);
} else {
int k = stk.top();
stk.pop();
dp[i] = i - k + 1;
if (k - 1 >= 0) {
dp[i] += dp[k-1];
}
if (dp[i] > longest) {
longest = dp[i];
}
}
}
return longest;
#endif
}
};