forked from javadev/LeetCode-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
47 lines (45 loc) · 1.21 KB
/
Solution.java
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
package g0001_0100.s0032_longest_valid_parentheses;
// #Hard #Top_100_Liked_Questions #String #Dynamic_Programming #Stack #Big_O_Time_O(n)_Space_O(1)
// #2023_08_09_Time_1_ms_(100.00%)_Space_41.4_MB_(85.22%)
public class Solution {
public int longestValidParentheses(String s) {
int max = 0;
int left = 0;
int right = 0;
int n = s.length();
char ch;
for (int i = 0; i < n; i++) {
ch = s.charAt(i);
if (ch == '(') {
left++;
} else {
right++;
}
if (right > left) {
left = 0;
right = 0;
}
if (left == right) {
max = Math.max(max, left + right);
}
}
left = 0;
right = 0;
for (int i = n - 1; i >= 0; i--) {
ch = s.charAt(i);
if (ch == '(') {
left++;
} else {
right++;
}
if (left > right) {
left = 0;
right = 0;
}
if (left == right) {
max = Math.max(max, left + right);
}
}
return max;
}
}