-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0020-valid-parentheses.c
73 lines (72 loc) · 1.65 KB
/
0020-valid-parentheses.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//?
typedef struct stack {
char* top;
char* base;
} stack;
void push(stack* a, char *s) {
*(a->top) = *s;
a->top++;
}
void pop(stack* a, char* data) {
*data = *--(a->top);
}
int isValid(char * s) {
int len = strlen(s);
if(len == 0) {
return true;
}
if(len % 2 != 0) {
return false;
}
stack *a = (stack*)malloc(sizeof(stack));
a->base = (char*)malloc(sizeof(char) * (len + 1));
a->top = a->base;
char * data = (char*)malloc(sizeof(char));
while(*s != '\0') {
if(')' == *s) {
if(a->top == a->base) {
return false;
} else {
pop(a, data);
if(*data != '(') {
a->top++;
return false;
} else {
*s++;
}
}
} else if('}' == *s) {
if(a->top == a->base) {
return false;
} else {
pop(a, data);
if(*data != '{') {
a->top++;
return false;
} else {
*s++;
}
}
} else if(']' == *s) {
if(a->top == a->base) {
return false;
} else {
pop(a, data);
if(*data != '[') {
a->top++;
return false;
} else {
*s++;
}
}
} else {
push(a, s);
*s++;
}
}
if(a->top == a->base) {
return true;
} else {
return false;
}
}