-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathValid_Nesting.c
53 lines (52 loc) · 1.58 KB
/
Valid_Nesting.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
/*
* Open brackets must be closed by the same type of brackets.
* Open brackets must be closed in the correct order.
* */
bool isValid(char *s) {
int SIZE = strlen(s);
char *ParenStack = (char *) calloc(SIZE, sizeof(char));
int i, LastStackIndex;
int StackIndex = 0;
for (i = 0; i < SIZE; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
ParenStack[StackIndex] = s[i];
StackIndex++;
} else {
if (!StackIndex) {
return 0;
}
LastStackIndex = StackIndex - 1;
switch (s[i]) {
case ')':
if (ParenStack[LastStackIndex] == '(') {
ParenStack[LastStackIndex] = '\0';
StackIndex--;
} else {
return 0;
}
break;
case ']':
if (ParenStack[LastStackIndex] == '[') {
ParenStack[LastStackIndex] = '\0';
StackIndex--;
} else {
return 0;
}
break;
case '}':
if (ParenStack[LastStackIndex] == '{') {
ParenStack[LastStackIndex] = '\0';
StackIndex--;
} else {
return 0;
}
break;
}
}
}
if (ParenStack[0] == '\0') {
return 1;
} else {
return 0;
}
}