思路:
遍歷s,遇到‘(’入棧,遇到‘)’且棧頂爲‘(’將棧頂出棧並計算長度。length=i-stack.peek()這樣可以將所有規範的長度計算出來。而遇到‘)’且棧頂不是‘(’說明0-i已經不能再形成規範的字符串,將i入棧,與之後的計算隔離。
public int longestValidParentheses(String s) {
Stack<Integer>stack=new Stack<Integer>();
stack.push(-1);
int max=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')stack.push(i);
else if(stack.peek()!=-1){
if(s.charAt(stack.peek())=='('){
stack.pop();
int length=i-stack.peek();
max=(max<length)?length:max;
}else{
stack.push(i);
}
}else{
stack.push(i);
}
}
return max;
}