File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 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 <stdio.h>
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+ }
You can’t perform that action at this time.
0 commit comments