给定一个只包含 '('
和 ')'
的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()" 输出: 2 解释: 最长有效括号子串为"()"
示例 2:
输入: ")()())"输出: 4 解释: 最长有效括号子串为 "()()"
public class Solution {
public int longestValidParentheses(String s) {
if (s==null||s.length()==0){
return 0;
}
int start=0;
int maxLen=0;
Stack<Integer> stack=new Stack<Integer>();
for (int i=0; i<s.length();i++){
if (s.charAt(i)=='('){
stack.push(i);
}else{
if (stack.isEmpty()){
start=i+1;
}else{
stack.pop();
if (stack.isEmpty()){
maxLen=Math.max(i-start+1, maxLen);
}
else{
maxLen=Math.max(i-stack.peek(),maxLen);
}
}
}
}
return maxLen;
}
}