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.
注意这道题的stack里面存的不是括号而是索引。这道题的标签中有动态规划,下次写注意一下动态规划的写法。
Source
public class Solution {
public int longestValidParentheses(String s) {
char a;
Stack<Integer> st = new Stack<Integer>(); //*****
int p = 0;
int cnt = 0;
for(int i = 0; i < s.length(); i++){
a = s.charAt(i);
if(a == '('){
st.push(i);
}
else if(a == ')'){
if(st.size() == 0){ //也可以用isEmpty
p = i + 1;
}
else{
st.pop();
if(st.isEmpty()){
cnt = Math.max(i - p + 1, cnt);
}
else{
cnt = Math.max(i - st.peek(), cnt);
}
}
}
}
return cnt;
}
}
Test
public static void main(String[] args){
String s = "(()";
System.out.println(new Solution().longestValidParentheses(s));
}