给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 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;
}
}

本文介绍了一种使用栈来解决寻找最长有效括号子串问题的方法。通过遍历输入字符串,利用栈记录左括号的位置,并在遇到右括号时进行匹配,以此来计算最长有效括号子串的长度。
520

被折叠的 条评论
为什么被折叠?



