算法分析与设计作业题
作业来源(hard)
public class Solution {
public int longestValidParentheses(String s) {
if(s == null || s.length()<=1) return 0;
int count = 0, max=0, depth = 0;
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(c == '(') depth++;
else{
depth--;
count++;
if(depth == 0) max = Math.max(max, count*2);
if(depth<0){
depth = 0;
count = 0;
}
}
}
depth = 0;
count = 0;
for(int i=s.length()-1; i>=0; i--){
char c = s.charAt(i);
if(c == ')') depth++;
else{
depth--;
count++;
if(depth == 0) max = Math.max(max, count*2);
if(depth<0){
depth = 0;
count = 0;
}
}
}
return max;
}
}