题目介绍:
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
For "(()"
, the longest valid parentheses substring is "()"
, which has length = 2.
Another example is ")()())"
, where the longest valid parentheses substring is "()()"
, which has length = 4.
Subscribe to see which companies asked this question
判断字符串是否是合法的函数如下:
public boolean isValid(String s){
if(s==null||s.length()<2)return false;
int len=s.length();
if(len%2!=0)return false;
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(') stack.push('(');
else{
if(stack.isEmpty())return false;
else stack.pop();
}
}
if(stack.isEmpty())return true;
return false;
}
本题目的解法代码如下:
public int longestValidParentheses(String s) {
if(s==null||s.length()<2)return 0;
int len=s.length();
Stack<Character> stack=new Stack<Character>();
Stack<Integer> stackNum=new Stack<Integer>();
boolean isValid[]=new boolean[len];
for(int i=0;i<len;i++) isValid[i]=false;
for(int i=0;i<len;i++){
if(s.charAt(i)=='('){
stack.push('(');
stackNum.push(i);
}
else{
if(!stack.isEmpty()){
stack.pop();
int k=stackNum.pop();
isValid[i]=true;
isValid[k]=true;
}
}
}
int result=0;
int max=0;
for(int i=0;i<len;i++){
if(isValid[i]){
result++;
while(i+1<len&&isValid[i+1]){
result++;
i++;
}
}else{
if(result>max)max=result;
result=0;
}
if(result>max)max=result;
}
return max;
}