Created
August 17, 2022 01:13
-
-
Save zoeisnowooze/5347717cfd57d564518ca41e6eeff83b to your computer and use it in GitHub Desktop.
Length of the longest valid parenthesis substring.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdbool.h> | |
#include <stdio.h> | |
int main(int argc, char **argv) { | |
int length, maxlength, stacksize; | |
length = maxlength = stacksize = 0; | |
while (true) { | |
int c; | |
c = getc(stdin); | |
if (c == '\n') { | |
/* Remove any left parenthesis that haven't been closed and check if that makes it the longest substring. */ | |
if (length - stacksize > maxlength) { | |
maxlength = length - stacksize; | |
} | |
printf("%d\n", maxlength); | |
length = maxlength = stacksize = 0; | |
} else if (c == EOF) { | |
putchar('\n'); | |
break; | |
} else if (c == '(') { | |
/* Substring gets longer and deeper. */ | |
length++; | |
stacksize++; | |
} else if (c == ')') { | |
/* Substring gets longer but shallower. */ | |
length++; | |
stacksize--; | |
if (stacksize == 0 && length > maxlength) { | |
/* Longest parenthesis substring completely closed, store its current length and continue counting. */ | |
maxlength = length; | |
} else if (stacksize < 0) { | |
/* Found an unmatched closing parenthesis, reset all counters. */ | |
length = 0; | |
stacksize = 0; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment