forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
df56917
commit 6567568
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test valid_parentheses.c |
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
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; | ||
} |