32. 最长有效括号
给你一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
示例 1:
输入:s = “(()”
输出:2
解释:最长有效括号子串是 “()”
示例 2:
输入:s = “)()())”
输出:4
解释:最长有效括号子串是 “()()”
示例 3:
输入:s = “”
输出:0
这题难度是困难,但是其实我觉得挺简单的
int in=0;
int find_vaild_max(char *s){
in=0;
int num=0;
if(s[0]==')'){
return 0;
}
int top=0;
int bottom=0;
int i=0;
top++;
i++;
num++;
while(s[i]!='\0'){
num++;
if(s[i]=='('){
top++;
}
else{
top--;
}
if(top==0){
in=i;
return num;
break;
}
i++;
}
return 0;
}
int longestValidParentheses(char * s){
int max=0;
int t=0;
int i=0;
while(s[i]!='\0'){
int num=find_vaild_max(s+i);
if(num>0){
i=i+in+1;
}
else{
i++;
}
if(num==0){
t=0;
}
else{
t=t+num;
if(t>max){
max=t;
}
}
}
return max;
}