-
Notifications
You must be signed in to change notification settings - Fork 1
/
6.括号匹配问题.c
89 lines (84 loc) · 1.46 KB
/
6.括号匹配问题.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
#include <stdio.h>
#define N 20
typedef struct Stack
{
char elements[N];
int len;
} Stack;
void init(Stack *s)
{
s->len = 0;
}
int isEmpty(Stack *s)
{
return s->len == 0;
}
void push(Stack *s, char c)
{
s->elements[s->len++] = c;
}
void getTop(Stack *s, char *c)
{
*c = s->elements[(s->len) - 1];
}
void pop(Stack *s)
{
(s->len)--;
}
int math(char a, char b)
{
switch (a)
{
case '(':
return b == ')';
case '[':
return b == ']';
case '{':
return b == '}';
}
return 0;
}
void brecketMath(char *str)
{
Stack s;
char ch;
init(&s);
for (int i = 0; str[i] != '\0'; i++)
{
switch (str[i])
{
case '(':
case '[':
case '{':
push(&s, str[i]);
break;
case ')':
case ']':
case '}':
if (!isEmpty(&s))
{
getTop(&s, &ch);
if (math(ch, str[i]))
pop(&s);
else
printf("不匹配\n");
}
else
printf("多余右括号\n");
}
}
if (isEmpty(&s))
printf("括号匹配\n");
else
printf("括号不匹配\n");
}
int main()
{
char *str1 = "{(x-y)*[(x+3y)/(7x-2y) - 10x]}";
printf("%s\n", str1);
brecketMath(str1);
char *str2 = "{(x-y)*[(x+3y)/(7x-2y - 10x";
printf("%s\n", str2);
brecketMath(str2);
return 0;
}