-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlec18.c
110 lines (95 loc) · 1.88 KB
/
lec18.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// bracket pair verifier
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
struct Node
{
int val;
struct Node *next;
};
int indexof(char C[], int n, int match)
{
for (int i = 0; i < n; i++)
{
if (C[i] == match)
return i;
}
return -1;
}
struct Node *create_node(int data)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->val = data;
temp->next = NULL;
return temp;
}
void print_linked_list(struct Node *start)
{
struct Node *temp = start;
while (temp != NULL)
{
printf("%c ", temp->val);
temp = temp->next;
}
printf("\n");
}
bool validate(char A[], int n)
{
struct Node *head = NULL;
char opening_arr[] = {'{', '(', '['};
char closing_arr[] = {'}', ')', ']'};
for (int i = 0; i < n; i++)
{
print_linked_list(head);
char c = A[i];
int opening = indexof(opening_arr, n, c);
if (opening >= 0)
{
struct Node *insert = create_node(c);
insert->next = head;
head = insert;
}
else
{
int closing = indexof(closing_arr, n, c);
if (closing < 0)
continue;
if (head == NULL)
{
return false;
}
else
{
char opening = head->val;
if (c == '}')
{
if (opening != '{')
return false;
}
else if (c == ']')
{
if (opening != '[')
return false;
}
else if (c == ')')
{
if (opening != '(')
return false;
}
head = head->next;
}
}
}
return head == NULL;
}
int main(void)
{
char A[] = {'[', '{', '(', 'a', '+', 'b', ')', '/', '2', '}', ']'};
char B[] = {'[', '{', '(', 'a', '+', 'b', ')', '/', '3', ')', '}'};
// assert(validate(A, 11));
// assert(!validate(B, 11));
printf("%d\n", validate(A, 11));
printf("%d\n", validate(B, 11));
return 0;
}