forked from int32bit/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve.c
41 lines (41 loc) · 739 Bytes
/
solve.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool isLeft(char c)
{
return c == '(' || c == '[' || c == '{';
}
bool isMatch(char a, char b)
{
return (a == '(' && b == ')')
|| (a == '[' && b == ']')
|| (a == '{' && b == '}');
}
bool isValid(char *s)
{
int len = strlen(s);
char *stack = malloc(sizeof(char) * len);
int pos = -1;
for (int i = 0; i < len; ++i) {
if (isLeft(s[i])) {
stack[++pos] = s[i];
} else {
if (isMatch(stack[pos], s[i])) {
--pos;
} else {
return false;
}
}
}
free(stack);
return pos == -1;
}
int main(int argc, char **argv)
{
char s[20];
printf("%d\n", isValid(""));
while (scanf("%s", s) != EOF)
printf("%d\n", isValid(s));
return true;
}