给你一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长有效(格式正确且连续)括号
子串的长度。
数据结构:栈
算法:使用栈进行模拟括号匹配,将可以匹配的括号对应位置置为0,求这个序列连续0的最长子序列长度。
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int i = 0,maxlen = 0;
StringBuffer str = new StringBuffer(s);
while(i < s.length()){
if(s.charAt(i) == '('){
stack.push(i);
str.setCharAt(i,'1');
}else{
if(!stack.isEmpty()){
int pos = stack.peek();
stack.pop();
str.setCharAt(pos,'0');
str.setCharAt(i,'0');
}
else
str.setCharAt(i,'1');
}
i++;
}
// System.out.println(str);
int len = 0;
for(int j = 0; j < str.length(); j++){
if(str.charAt(j) == '1'){
len = 0;
continue;
}
len++;
maxlen = Math.max(len,maxlen);
}
return maxlen;
}
}
进一步优化,可以直接计算最长序列
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
int i = 0,maxlen = 0;
stack.push(-1);
while(i < s.length()){
if(s.charAt(i) == '('){
stack.push(i);
}else{
//先将(出栈,注意第一个可能是)
//这样一直保证栈底是上一对括号的前一个位置
stack.pop();
if(stack.isEmpty()){
//持续是),同样保证栈底是上一对括号的前一个位置
stack.push(i);
}else{
int pos = stack.peek();
maxlen = Math.max(maxlen,i-pos);
}
}
i++;
}
return maxlen;
}
}