-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path32. Longest Valid Parentheses.cpp
52 lines (47 loc) · 1.36 KB
/
32. Longest Valid Parentheses.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
/*********** Method-1 (Using stack, Kadane's type, TC-O(N), SC-O(N)) **************
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size();
stack<int> stk;
stk.push(-1);
int res = 0;
for(int i = 0; i < n; i++) {
if(s[i] == '(') {
stk.push(i);
}
else {
stk.pop();
if(stk.empty())
stk.push(i);
else
res = max(res, i-stk.top());
}
}
return res;
}
};
*******************************************************************************************/
/************** Method-2 (Bottom-Up, TC-O(N), SC-O(N)) **********************************/
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size(), i, j, res = 0;
vector<int> dp(n, 0);
// dp[0] = 0;
for(i = 1; i < n; i++) {
if(s[i] == '(')
dp[i] = 0;
else {
j = i - dp[i-1] - 1;
if(j >= 0 && s[j] == '(') {
dp[i] = dp[i-1] + 2;
if(j-1 >= 0)
dp[i] += dp[j-1];
}
}
res = max(res, dp[i]);
}
return res;
}
};