设计一个函数 int bracketmatch(char* str) 该函数的功能判断由str字符串所给出的表达式里圆括号、方括号、花括号是否合法,也就是左右匹配。对其它字符符合不做任何判断。(1 + 35)) 不合法;[3] + {444} - [(333)]合法;{ 1 + [233 } - ]不合法;合法返回1,不合法返回0
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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
| #include <stdio.h> #define Stack_Size 100 #define TRUE 1 #define FALSE 0
typedef struct { char elem[Stack_Size]; int top; }SeqStack;
void InitStack(SeqStack* s) { s->top = -1; }
int IsEmpty(SeqStack* s) { if (s->top == -1) { return TRUE; } else { return FALSE; } }
int IsFull(SeqStack* s) { if (s->top == -1) { return TRUE; } else { return FALSE; } }
int Push(SeqStack* s, char e) { if (s->top == Stack_Size - 1) return FALSE; s->top++; s->elem[s->top] = e; return TRUE; }
int Pop(SeqStack* s, char* e) { if (s->top == -1) return FALSE; *e = s->elem[s->top]; s->top--; return TRUE; }
int GetTop(SeqStack* s, char* e) { if (s->top == -1) return FALSE; *e = s->elem[s->top]; return TRUE; }
int bracketmatch(char* str) { char ch, ch1; SeqStack s;
InitStack(&s);
while (*str != '\0') { ch = *str; if (ch == '(' || ch == '[' || ch == '{') Push(&s, ch); else if (ch == ')') { if (!GetTop(&s, &ch1)) return FALSE; if (ch1 == '(') Pop(&s, &ch1); else return FALSE; } else if (ch == ']') { if (!GetTop(&s, &ch1)) return FALSE; if (ch1 == '[') Pop(&s, &ch1); else return FALSE; } else if (ch == '}') { if (!GetTop(&s, &ch1)) return FALSE; if (ch1 == '{') Pop(&s, &ch1); else return FALSE; }
str++; } return IsEmpty(&s);
}
int main(int argc, char* argv[]) { char* str = "(1+5)*6 + ({3-5 + [5*9] +4}-6)"; char* str1 = "(1+5)*6 + ({3-5 + [5*9] +4}-6)}"; if (bracketmatch(str)) printf("str bracket match OK!\n"); else printf("str bracket match ERROR!\n");
if (bracketmatch(str1)) printf("str1 bracket match OK!\n"); else printf("str1 bracket match ERROR!\n");
return 0; }
|