給定一個只包含 ‘(’ 和 ‘)’ 的字符串,找出最長的包含有效括號的子串的長度。
示例 1:
輸入: “(()”
輸出: 2
解釋: 最長有效括號子串爲 “()”
class Solution {
public int longestValidParentheses(String s) {
if(s==null||s.length()==0)//很自然的想到用棧
return 0;
int max=0;
Stack<Integer> stack=new Stack<>();
stack.push(-1);
for(int i=0;i!=s.length();i++){
if(s.charAt(i)=='('){
stack.push(i);
}
if(s.charAt(i)==')'){
stack.pop();
if(stack.isEmpty())
stack.push(i);
else
max=max>i-stack.peek()?max:i-stack.peek();
}
}
return max;
}
}