Longest Valid Parentheses, longestparentheses
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.
Problem description: Given a string that only contains "(" and ")", find the longest sub-string that complies with the rules.
For "()", the longest valid substring is "()", so the length is 2
In another example, ") ()", the longest Valid String is "()", so the length is 4.
Solution:
(1) apply for an integer array with the same length as the input string. The initialization values are all-1, and the array and the input string have a one-to-one correspondence relationship;
(2) When the input string traversal Encounters "(", the corresponding position is subscript into the stack;
(3) When ")" is encountered, the value of the corresponding position of the array is set to 0, the first value in the stack is displayed, and the corresponding position of the integer array is set to 0, in this way, the corresponding "()" is ensured, and their corresponding values in the integer array are 0;
(4) When the traversal ends, finding the maximum number of consecutive Zeros is the required result.
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