-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestValidParens.java
36 lines (36 loc) · 1.25 KB
/
LongestValidParens.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
import java.util.Stack;
public class LongestValidParens{
public int longestValidParentheses(String s){
int cur = 0;
int max = 0;
if(s != null){
Stack<Character> st = new Stack<Character>();
int i = 0;
while(i < s.length()){
char c = s.charAt(i);
if(c == '(' || c == '[' || c == '{')
st.push(c);
else if(st.isEmpty() || (st.peek() != '[' && c == ']') ||
(st.peek() != '{' && c == '}') || (st.peek() != '(' && c == ')')){
max = (max < cur)? cur : max;
cur = 0;
st.push(c);
}
else{
st.pop();
cur += 2;
}
i++;
}
}
max = (max < cur)? cur : max;
return max;
}
public static void main(String[] argvs){
LongestValidParens vp = new LongestValidParens();
System.out.println(vp.longestValidParentheses("(()"));
System.out.println(vp.longestValidParentheses(")()())"));
System.out.println(vp.longestValidParentheses("(]"));
System.out.println(vp.longestValidParentheses("(])]"));
}
}