LeetCode-032-最长有效括号
思路
一般括号匹配的问题都会使用栈来解决,将左括号入栈,右括号匹配则出栈,然后标记为1,表示是有效匹配,只需找到连续为1的最长长度即可
代码
class Solution {
public int longestValidParentheses(String s) {
int []mark=new int[s.length()];//用于标记是否为有效括号,初始化为0,有效为1
Stack<Integer> st=new Stack<>();//仅入栈左括号,有右括号匹配则出栈
char []ch=s.toCharArray();
for(int i=0;i<s.length();i++){
//左括号入栈
if(ch[i]=='(')st.push(i);
else{
//栈空直接continue
if(st.isEmpty()){
continue;
}
//否则进行匹配标记
else {
int j=st.pop();
mark[j]=1;
mark[i]=1;
}
}
}
int max=0;
int cur=0;
for(int i=0;i<s.length();i++){
if(mark[i]==1)cur++;
else{
max=Math.max(max,cur);
cur=0;
}
}
max=Math.max(max,cur);
//这个要再比较一次,因为可能最后都是1,如果都是1,那么else没被执行过
return max;
}
}