-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValid Parenthesis.c
More file actions
62 lines (53 loc) · 1.23 KB
/
Copy pathValid Parenthesis.c
File metadata and controls
62 lines (53 loc) · 1.23 KB
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
char stack[MAX];
int top = -1;
void push(char c) {
if (top >= MAX - 1) {
printf("Stack overflow!\n");
exit(1);
}
stack[++top] = c;
}
char pop() {
if (top == -1) {
printf("Stack underflow!\n");
exit(1);
}
return stack[top--];
}
int isEmpty() {
return top == -1;
}
int isBalanced(const char* str) {
for (int i = 0; str[i] != '\0'; i++) {
char c = str[i];
if (c == '(' || c == '[' || c == '{') {
push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (isEmpty()) {
return 0;
}
char topChar = pop();
if ((c == ')' && topChar != '(') ||
(c == ']' && topChar != '[') ||
(c == '}' && topChar != '{')) {
return 0;
}
}
}
return isEmpty();
}
int main() {
char str[100];
printf("Enter a string with parentheses, square brackets, and curly braces: ");
scanf("%s", str);
if (isBalanced(str)) {
printf("The string is balanced.\n");
} else {
printf("The string is not balanced.\n");
}
return 0;
}