forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0020-valid-parentheses.c
80 lines (69 loc) · 1.68 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
74
75
76
77
78
79
80
struct Node {
char val;
struct Node* next;
};
struct Stack {
struct Node* head;
size_t len;
};
struct Node* Node(char val, struct Node* next) {
struct Node* root = (struct Node*)malloc(sizeof(struct Node));
root -> next = next;
root -> val = val;
return root;
}
struct Stack* Stack() {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack -> len = 0;
stack -> head = NULL;
return stack;
}
void append(struct Stack* stack, char val) {
struct Node* node = Node(val, stack -> head);
stack -> head = node;
stack -> len += 1;
}
char pop(struct Stack* stack) {
if (stack -> head == NULL) {
return NULL;
}
char val = stack -> head -> val;
struct Node* deleteNode = stack -> head;
stack -> head = stack -> head -> next;
stack -> len -= 1;
free(deleteNode);
return val;
}
void freeStack(struct Stack* stack) {
while (pop(stack) != NULL) {
pop(stack);
}
free(stack);
}
char opposite_parenthesis(char closing) {
char opening = NULL;
if (closing == ')') {
opening = '(';
} else if (closing == '}') {
opening = '{';
} else if (closing == ']') {
opening = '[';
}
return opening;
}
bool isValid(char * s){
struct Stack* stack = Stack();
char* chr;
for (chr = s; *chr != '\0'; chr++) {
if (opposite_parenthesis(*chr) == NULL) {
append(stack, *chr);
} else if (stack -> len != 0 && opposite_parenthesis(*chr) == pop(stack)) {
continue;
} else {
return false;
}
}
bool result = stack -> len == 0;
freeStack(stack);
return result;
}