描述
假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,如 () 或 [([][])] 等为正确的匹配,[(]) 或( 或 (()) 均为错误的匹配。 现在的问题是,要求检验一个给定表达式中的括弧是否正确匹配? 输入一个只包含圆括号和方括号的字符串,判断字符串中的括号是否匹配,匹配就输出 “OK” ,不匹配就输出“Wrong”。输入一个字符串:[([][])],输出:OK。
格式
输入格式
输入仅一行字符(字符个数小于255)。
输出格式
匹配就输出 “OK” ,不匹配就输出“Wrong”。
样例
输入样例
[(])
输出样例
Wrong
#include<stdio.h>
char stack[256];
int match(){
int top=-1;
char str[256];
gets(str);
int i=0;
while(str[i]!='\0'){
if(str[i]=='('||str[i]=='['){
stack[++top]=str[i];
}else if(str[i]==')'||str[i]==']'){
if(top==-1){
printf("Wrong");
return 0;
}
if((str[i]==')'&&stack[top]=='(')||(str[i]==']'&&stack[top]=='[')){
stack[top--];
}else{
printf("Wrong");
return 0;
}
}
i++;
}
if(top==-1){
printf("OK");
return 0;
}else{
printf("Wrong");
return 0;
}
}
int main(){
match();
return 0;
}
743

被折叠的 条评论
为什么被折叠?



