Skip to content

Commit f465a7d

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 32_Longest_Valid_Parentheses.java
1 parent 3d345cf commit f465a7d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public int longestValidParentheses(String s) {
3+
if (s == null || s.length() == 0) {
4+
return 0;
5+
}
6+
7+
int[] dp = new int[s.length()];
8+
dp[0] = 0;
9+
int leftBracketCount = 0, result = 0;
10+
11+
for (int i = 0; i < s.length(); i++) {
12+
if (s.charAt(i) == '(') {
13+
++leftBracketCount;
14+
} else if (leftBracketCount > 0) {
15+
dp[i] = dp[i - 1] + 2;
16+
17+
if (i - dp[i] > 0) {
18+
dp[i] += dp[i - dp[i]];
19+
}
20+
21+
--leftBracketCount;
22+
result = Math.max(result, dp[i]);
23+
}
24+
}
25+
26+
return result;
27+
}
28+
}

0 commit comments

Comments
 (0)