数据结构实验之栈四:括号匹配
Time Limit: 1000MS Memory limit: 65536K
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入
输入数据有多组,处理到文件结束。
输出
如果匹配就输出“yes”,不匹配输出“no”
示例输入
sin(20+10) {[}]
示例输出
yes no
注意:读入的字符串里可能含有空格哦!
#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <map>
#include <stack>
#include <deque> //双端队列
#include <queue>
#include <algorithm>
#include <ctype.h>
using namespace std;
int main()
{
char s[100];
int i, j;
while(gets(s)!=NULL)
{
unsigned int len=strlen(s);
stack<char>q;
for(i=0; i<len; i++)
{
if(s[i]=='(' || s[i]=='[' ||s[i]=='{')
{
q.push(s[i]);
}
else if(s[i]==')')
{
if(q.empty() || q.top()!='(')
{
q.push(s[i]);
}
else if(q.top()=='(')
{
q.pop();
}
}
else if(s[i]==']')
{
if(q.empty() || q.top()!='[')
{
q.push(s[i]);
}
else if(q.top()=='[')
{
q.pop();
}
}
else if(s[i]=='}')
{
if(q.empty() || q.top()!='{')
{
q.push(s[i]);
}
else if(q.top()=='{')
{
q.pop();
}
}
}
if(q.empty())
printf("yes\n");
else
printf("no\n");
}
return 0;
}