Skip to content

Instantly share code, notes, and snippets.

@zoeisnowooze
Created August 17, 2022 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoeisnowooze/5347717cfd57d564518ca41e6eeff83b to your computer and use it in GitHub Desktop.
Save zoeisnowooze/5347717cfd57d564518ca41e6eeff83b to your computer and use it in GitHub Desktop.
Length of the longest valid parenthesis substring.
#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