题目描述
AC代码
/*
括号序列合法<=>所有前缀和>=0,且总和等于0
(())
1 1 -1 -1
start 当前枚举的这一端的开头
cnt 前缀和
cnt<0 那么 start=i,cnt=0
cnt>0 那么 继续做
cnt==0 那么 [start,i]时合法的括号序列
*/
class Solution {
public int longestValidParentheses(String s) {
int res=work(s);
System.out.println(res);
s=new StringBuilder(s).reverse().toString();
char[] ch=s.toCharArray();
//(和)的ascii码可以发现一个是28一个是29,差别在于最后一位不同,可以通过^改变.
for(int i=0;i<ch.length;i++)
ch[i]^=1;
s=new String(ch);
return Math.max(res,work(s));
}
public int work(String s){
int res=0;
for(int i=0,start=0,cnt=0;i<s.length();i++){
if(s.charAt(i)=='(')
cnt++;
else
{
cnt--;
if(cnt<0){
start=i+1;cnt=0;
}else
{
if(cnt==0) res=Math.max(res,i-start+1);
}
}
}
return res;
}
}
通过堆栈来解题。
class Solution {
public int longestValidParentheses(String s) {
assert s != null;
if (s.length() < 2) {
return 0;
}
Stack<Integer> stack = new Stack<>();
int max = 0;
stack.add(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.isEmpty()) {
stack.push(i);
} else {
max = max > (i - stack.peek()) ? max : (i - stack.peek());
}
}
}
return max;
}
}