-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path20_valid_parentheses.c
56 lines (48 loc) · 1.06 KB
/
20_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
#include <assert.h>
#include <stdlib.h>
#include <string.h>
typedef struct Stack {
int *base;
int top;
int size;
}Stack;
void push(Stack* stack, int e) {
stack->base[stack->top++] = e;
}
int pop(Stack* stack) {
return stack->base[--(stack->top)];
}
int empty(Stack* stack) {
return stack->top==0;
}
Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->base = (int *)malloc(sizeof(int)*1000);
stack->size = 1000;
stack->top = 0;
return stack;
}
int isValid(char* s) {
Stack* stack = createStack();
int i = 0;
int len = strlen(s);
char c;
for(i = 0; i < len; i++) {
c = s[i];
if(c=='{' || c=='(' || c=='[')
push(stack, c);
else if(c=='}' || c==')' || c==']') {
if(empty(stack))
return 0;
char temp = pop(stack);
if(temp-c > 2)
return 0;
}
}
return empty(stack);
}
int main() {
assert(isValid("((({{[[[]]]}})))") == 1);
assert(isValid("({[}])") == 0);
return 0;
}