Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
public class Solution {
public int longestValidParentheses(String s) {
Stack<int[]> record = new Stack<>();
int max = 0;
for(int i = 0; i < s.length(); i++){
int currentSymbol = s.charAt(i) == '('? 1 : 2;
if(currentSymbol == 1){
record.push(i * 10 + 1);
}
else{
if(record.empty() || record.peek() % 10 == 2)
record.push(i * 10 + 2);
else{
record.pop();
int localLength = 0;
if(record.empty()){
localLength = i + 1;
}
else{
localLength = i - record.peek() / 10;
}
max = Math.max(max, localLength);
}
}
}
return max;
}
}