-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode2
81 lines (67 loc) · 1.91 KB
/
code2
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
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
// Structure to represent a stack
struct Stack {
char data[100];
int top;
};
// Function to initialize an empty stack
void initStack(struct Stack* s) {
s->top = -1;
}
// Function to push an element onto the stack
void push(struct Stack* s, char c) {
s->data[++s->top] = c;
}
// Function to pop an element from the stack
char pop(struct Stack* s) {
if (s->top == -1) {
return '\0';
}
return s->data[s->top--];
}
// Function to check if a character is an opening parenthesis
bool isOpening(char c) {
return (c == '(' || c == '{' || c == '[');
}
// Function to check if a character is a closing parenthesis
bool isClosing(char c) {
return (c == ')' || c == '}' || c == ']');
}
// Function to check if two characters form a valid pair of parentheses
bool isValidPair(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']');
}
// Function to check the validity of parentheses in a string
bool isValidParentheses(char* str) {
struct Stack stack;
initStack(&stack);
int len = strlen(str);
for (int i = 0; i < len; i++) {
char current = str[i];
if (isOpening(current)) {
push(&stack, current);
} else if (isClosing(current)) {
if (stack.top == -1 || !isValidPair(stack.data[stack.top], current)) {
return false; // Unmatched or invalid pair
} else {
pop(&stack);
}
}
}
return (stack.top == -1); // Stack should be empty if all parentheses are matched.
}
int main() {
char input[100];
printf("Enter a string with parentheses: ");
scanf("%s", input);
if (isValidParentheses(input)) {
printf("Valid parentheses\n");
} else {
printf("Invalid parentheses\n");
}
return 0;
}