File tree Expand file tree Collapse file tree 1 file changed +16
-19
lines changed
032_longest_valid_parentheses Expand file tree Collapse file tree 1 file changed +16
-19
lines changed Original file line number Diff line number Diff line change 11#include <stdio.h>
22#include <stdlib.h>
33
4+
45static int longestValidParentheses (char * s )
56{
6- int cap = 8000 , error = -1 ;
7- int length = 0 , max_length = 0 ;
8- char * p = s ;
7+ int i , cap = 18000 , invalid = -1 ;
8+ int len = 0 , max_len = 0 ;
99 int * stack = malloc (cap * sizeof (int ));
1010 int * top = stack ;
1111
12- while (* p != '\0' ) {
13- if (* p == '(' ) {
14- if (top + 1 - stack >= cap ) {
15- cap *= 2 ;
16- stack = realloc (stack , cap * sizeof (int ));
17- }
18- * top ++ = p - s ;
12+ /* We only restore index of '(' since restrain of space */
13+ for (i = 0 ; s [i ] != '\0' ; i ++ ) {
14+ if (s [i ] == '(' ) {
15+ * top ++ = i ;
1916 } else {
2017 if (top > stack ) {
2118 if (-- top == stack ) {
22- /* The stack never keep ')' so we use 'error' to record index */
23- length = p - ( s + error ) ;
19+ /* distancd of the latest ')' */
20+ len = i - invalid ;
2421 } else {
25- /* The *(top - 1) is the index of the last kept '(' */
26- length = p - ( s + * (top - 1 ) );
22+ /* distance of the remote '(' */
23+ len = i - * (top - 1 );
2724 }
28- if (length > max_length ) {
29- max_length = length ;
25+ if (len > max_len ) {
26+ max_len = len ;
3027 }
3128 } else {
32- error = p - s ;
29+ /* record the index of last ')' but no push */
30+ invalid = i ;
3331 }
3432 }
35- p ++ ;
3633 }
37- return max_length ;
34+ return max_len ;
3835}
3936
4037int main (int argc , char * * argv )
You can’t perform that action at this time.
0 commit comments