Skip to content

Commit 0ba3532

Browse files
add problem 32 and test function
1 parent 619faf9 commit 0ba3532

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

C/1-50/32-Longest-Valid-Parentheses.c

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/*
2+
* Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
3+
4+
* For "(()", the longest valid parentheses substring is "()", which has length = 2.
5+
6+
* Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
7+
* Created by supercoderx on 2017/8/12.
8+
*/
9+
#include
10+
int longestValidParentheses(char* s) {
11+
int len = 0;
12+
char* ch = s;
13+
while(*ch!='\0'){
14+
ch++;
15+
len++;
16+
}
17+
if(len == 0)
18+
return 0;
19+
int stack[len],top = -1, longest = -1;
20+
for(int i = 0;i < len;i++){
21+
if(s[i]=='(')
22+
stack[++top] = i;
23+
else{
24+
if(top>-1){
25+
if(s[stack[top]] == '(')
26+
top--;
27+
else
28+
stack[++top] = i;
29+
}else
30+
stack[++top] = i;
31+
}
32+
}
33+
if(top == -1)
34+
return len;
35+
36+
int a=len,b,curLen = -1;
37+
while(top>-1){
38+
b = stack[top];
39+
curLen = a-b-1;
40+
longest = longest>curLen?longest:curLen;
41+
a = b;
42+
top--;
43+
}
44+
return a>longest?a:longest;
45+
}
46+
47+
void testLongestValidParentheses(){
48+
char* s1 = "()(())";
49+
printf("%d",longestValidParentheses(s1));
50+
}

0 commit comments

Comments
 (0)