Skip to content

Commit

Permalink
Valid parentheses
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 2, 2017
1 parent df56917 commit 6567568
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 020_valid_parentheses/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test valid_parentheses.c
47 changes: 47 additions & 0 deletions 020_valid_parentheses/valid_parentheses.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

static bool isValid(char *s)
{
int n = 0, cap = 100;
char *stack = malloc(cap);

while (*s != '\0') {
switch(*s) {
case '(':
case '[':
case '{':
if (n + 1 >= cap) {
cap *= 2;
stack = realloc(stack, cap);
}
stack[n++] = *s;
break;
case ')':
if (stack[--n] != '(') return false;
break;
case ']':
if (stack[--n] != '[') return false;
break;
case '}':
if (stack[--n] != '{') return false;
break;
default:
return false;
}
s++;
}

return n == 0;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test xxxx");
exit(-1);
}
printf("%s\n", isValid(argv[1]) ? "true" : "false");
return 0;
}

0 comments on commit 6567568

Please sign in to comment.