赞
踩
判断括号是否匹配:给定n组数,每组为一个字符串,测试3种括号:{},[],(),且顺序只能是先左括号,后右括号,括号间可以嵌套。若匹配成功则输出yes,否则输出no;
如:{@}a、{[()]} 都是匹配;
{[[]}、{}{ 都是不匹配。
2
{a}[b](d)
{[(]}
yes
no
该问题用栈来解决
#include<stdio.h> #include<math.h> #include<string.h> #define MaxSize 10 //交换函数 void swap(int &a,int &b){ int t; t=a; a=b; b=t; } typedef struct { char data[MaxSize]; int top; }SeqStack; //初始化栈 void InitStack(SeqStack &s){ s.top=-1; } //判断栈是否为空 bool StackEmpty(SeqStack &s){ if(s.top==-1) return true; else return false; } //进栈 bool push(SeqStack &s,char x){ if(s.top==MaxSize-1) return false; s.top++; s.data[s.top]=x; return true; } //出栈 bool pop(SeqStack &s,char &x){ if(s.top==-1) return false; x=s.data[s.top]; s.top--; return true; } //匹配算法 bool check(char str[],int l){ SeqStack s; InitStack(s); for(int i=0;i<l;i++){ if(str[i]=='('||str[i]=='['||str[i]=='{'){ push(s,str[i]); } else { if(StackEmpty(s)) return false; //当是右括号是判断是否匹配,把字母过滤掉 if(str[i]==')'||str[i]==']'||str[i]=='}'){ char topElem; pop(s,topElem); if(str[i]==')'&&topElem!='(') return false; if(str[i]==']'&&topElem!='[') return false; if(str[i]=='}'&&topElem!='{') return false; } } } //检测完后还需要判断栈是否空,如果不空则匹配不成功 return StackEmpty(s); } int main(){ int n,m; scanf("%d\n",&n); char c; char str[20]; while(n--){ int l=0; while((c=getchar())!='\n'){ str[l]=c; l++; } if(check(str,l)) printf("yes\n"); else printf("no\n"); } return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。