Skip to content

Commit 2866c4f

Browse files
committed
Improved task 32.
1 parent 10c594a commit 2866c4f

File tree

1 file changed

+35
-16
lines changed
  • src/main/java/g0001_0100/s0032_longest_valid_parentheses

1 file changed

+35
-16
lines changed

src/main/java/g0001_0100/s0032_longest_valid_parentheses/Solution.java

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,42 @@
11
package g0001_0100.s0032_longest_valid_parentheses;
22

33
public class Solution {
4-
public int longestValidParentheses(String symbols) {
4+
public int longestValidParentheses(String s) {
55
int max = 0;
6-
char[] s = symbols.toCharArray();
7-
int[] dp = new int[s.length];
8-
for (int i = 1; i < s.length; i++) {
9-
if (s[i] == ')') {
10-
if (s[i - 1] == '(') {
11-
dp[i] = 2;
12-
dp[i] += (i >= 2) ? dp[i - 2] : 0;
13-
} else {
14-
if (i - dp[i - 1] - 1 >= 0 && s[i - dp[i - 1] - 1] == '(') {
15-
dp[i] = 2;
16-
dp[i] += dp[i - 1];
17-
dp[i] += ((i - dp[i - 1]) >= 2) ? dp[i - dp[i - 1] - 2] : 0;
18-
}
19-
}
20-
max = Math.max(max, dp[i]);
6+
int left = 0;
7+
int right = 0;
8+
int n = s.length();
9+
char ch;
10+
for (int i = 0; i < n; i++) {
11+
ch = s.charAt(i);
12+
if (ch == '(') {
13+
left++;
14+
} else {
15+
right++;
16+
}
17+
if (right > left) {
18+
left = 0;
19+
right = 0;
20+
}
21+
if (left == right) {
22+
max = Math.max(max, left + right);
23+
}
24+
}
25+
left = 0;
26+
right = 0;
27+
for (int i = n - 1; i >= 0; i--) {
28+
ch = s.charAt(i);
29+
if (ch == '(') {
30+
left++;
31+
} else {
32+
right++;
33+
}
34+
if (left > right) {
35+
left = 0;
36+
right = 0;
37+
}
38+
if (left == right) {
39+
max = Math.max(max, left + right);
2140
}
2241
}
2342
return max;

0 commit comments

Comments
 (0)