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.
问题描述:给定一个只包含“(”和")"的串,找出一个最长的符合规则的子串。
对于“(()”,最长有效子串是“()”,所以长度是2
另一个例子,“)()())”,最长的有效字串是“()()”,所以长度是4.
解题思路:
(1)申请一个与输入串长度相同的整型数组,初始化值全部为-1,数组和输入串有一一对应的关系;
(2)遍历输入串遇到“(”,就将其对应位置下标入栈;
(3)遇到“)”,就将数组对应位置的值设置为0,弹出栈中第一个值,并将整型数组对应位置置0,这样保证对应的“()”,它们在整型数组中对应的值是0;
(4)遍历结束,寻找0的连续个数最大值,就是要求的结果。



int longestValidParentheses(char* s) {
int slen=strlen(s);
if(slen<=1)return 0;
int* index=(int*)malloc(sizeof(int)*slen);
for(int i=0;i<slen;i++)index[i]=-1;
int* stack=(int*)malloc(sizeof(int)*slen);
int top=0;
for(int i=0;i<slen;i++)
if(s[i]=='(')stack[top++]=i;
else{
if(top!=0){
index[stack[top-1]]=0;
index[i]=0;
top--;
}
}
int count=0;
int newCount=0;
for(int i=0;i<slen;i++)
if(index[i]!=-1)newCount++;
else{
if(newCount>count){
count=newCount;
}
newCount=0;
}
if(newCount>count)count=newCount;
return count;
} View Code