给出一组括号,用程序判断这组括号能否正确匹配。
用数据结构中的栈,将左括号入栈,如果遇到匹配的右括号,则出栈。 最后,如果栈为空,说明完全匹配。
void pipei()
{
char s[] = "([{}((()}}}])";
//char s[] = "([{}()])";
char z[100];
int top = 0;
for (int i = 0; i < 8; i++) {
// 左括号 入栈
if (strncmp(&s[i],"(",1) == 0||
strncmp(&s[i],"[",1) == 0||
strncmp(&s[i],"{",1) == 0) {
z[++top] = s[i];
}
else {
// 右括号 匹配
char *left = &z[top];
char *right = &s[i];
if ((strncmp(left,"(",1) && strncmp(right,")",1)) ||
(strncmp(left,"{",1) && strncmp(right,"}",1)) ||
(strncmp(left,"[",1) && strncmp(right,"]",1))) {
// 出栈
top--;
}
else {
break;
}
}
}
// print
if (top == 0) {
printf("匹配\n" );
}
else {
printf("不匹配\n" );
}
}