Level:
Medium
题目描述:
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
思路分析:
设置一个栈,遍历字符串,如果遇到‘(’,将它对应的下标存放进栈,遇到‘)’,其下标为i,弹出栈顶元素,计算 i-stack.pop()更新res,直到遍历结束,得到最大的res。
代码:
public class Solution{
public int longestValidParentheses(String s){
Stack<Integer>stack=new Stack<>();
int left=-1;
int res=0;
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')
stack.push(i);
else{
if(stack.isEmpty())
left=i; //一开始出现‘)’
else{
stack.pop();
if(stack.isEmpty())
res=Math.max(res,i-left);
else
res=Math.max(res,i-stack.peek());
}
}
}
return res;
}
}