-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32.java
More file actions
33 lines (32 loc) · 861 Bytes
/
32.java
File metadata and controls
33 lines (32 loc) · 861 Bytes
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
class Solution {
public int longestValidParentheses(String str) {
Stack<Integer> st = new Stack<>();
st.push(-1);
int maxLen = 0;
int n=str.length();
for(int i=0;i<n;i++){
if(str.charAt(i)=='('){
st.push(i);
}
else{
st.pop();
if(st.isEmpty()){
st.push(i);
}
else{
maxLen=Math.max(maxLen,i-st.peek());
}
}
}
return maxLen;
}
}
// Approach:
// use stack.
// first push -1 as a base.
// for loop thru string.
// if ch==( push
// else {
// pop.
// now if stack is empty push current index, so that length calculation is done from there then onwards.
// otherwise if stack has values, calculate max value