forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestValidParentheses.java
39 lines (32 loc) · 962 Bytes
/
LongestValidParentheses.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
class Solution {
// TC : O(n)
// SC : O(n)
public int longestValidParentheses(String s) {
if(s==null || s.length()<2){
return 0;
}
Stack<Integer> st =new Stack<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i) == '('){
st.push(i);
} else{
// current closing bracket
if(!st.empty() && s.charAt(st.peek()) == '('){
// balanced case
st.pop();
} else {
// unbalanced case
st.push(i);
}
}
}
int maxLen = 0;
int endTerminal = s.length();
while(!st.empty()){
int startTerminal = st.pop();
maxLen = Math.max(maxLen, endTerminal - startTerminal -1);
endTerminal = startTerminal;
}
return Math.max(endTerminal, maxLen);
}
}