-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0032_Longest_Valid_Parentheses.java
52 lines (46 loc) · 1.35 KB
/
0032_Longest_Valid_Parentheses.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
48
49
50
51
52
/*
* 32. Longest Valid Parentheses
* Problem Link: https://leetcode.com/problems/longest-valid-parentheses/
* Difficulty: Hard
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public int longestValidParentheses(String s) {
int left = 0;
int right = 0;
int result = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (right == left) {
result = Math.max(result, 2 * left);
} else if (right > left) { // ())
left = right = 0;
}
}
// for cases like (()
// also count from backwards
left = right = 0;
for (int i = s.length()-1; i >= 0; i--) {
System.out.println("left="+left+", right = " +right);
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (right == left) {
result = Math.max(result, 2 * left);
} else if (left > right) { // (()
left = right = 0;
}
}
return result;
}
}