-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParentheses.java
More file actions
38 lines (36 loc) · 1.07 KB
/
LongestValidParentheses.java
File metadata and controls
38 lines (36 loc) · 1.07 KB
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
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/*
* https://leetcode.com/problems/longest-valid-parentheses/
*/
public class LongestValidParentheses {
public int longestValidParentheses(String s) {
if (s.isEmpty()) {
return 0;
}
int count = 0;
int maxValid = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
count++;
} else {
if (count == 0) {
return Math.max(maxValid, longestValidParentheses(s.substring(i + 1)));
}
count--;
if (count == 0) {
maxValid = Math.max(i + 1, maxValid);
}
}
}
if (count == 0) {
return s.length();
}
return Math.max(maxValid, longestValidParentheses(s.substring(1)));
}
public static void main(String[] args) {
System.out.println(new LongestValidParentheses().longestValidParentheses(")()())")); // 4
}
}