数据结构实验之栈四:括号匹配
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入
输入数据有多组,处理到文件结束。
输出
如果匹配就输出“yes”,不匹配输出“no”
示例输入
sin(20+10) {[}]
示例输出
yes no
提示
栈的基础应用,对字符串遍历,左括号入栈,出现右括号如果与栈顶左括号匹配则弹出栈顶,否则就不匹配,最后栈顶元素为0则输出yes,代码如下:
#include <bits/stdc++.h>
using namespace std;
typedef char anytype;
struct stacks
{
struct node //链栈
{
anytype data;
struct node *next;
}*head;
stacks() //构造函数
{
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
}
bool empty() //判断空栈
{
if(head->next)
return false;
return true;
}
void push(anytype n) //入栈
{
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
p->data=n;
p->next=head->next;
head->next=p;
}
void pop() //出栈
{
struct node *p;
p=head->next;
if(p)
{
head->next=p->next;
free(p);
}
}
anytype top() //查询栈顶元素
{
if(!empty())
return head->next->data;
return 0;
}
};
bool isBrackets(char ch) //判断是否为括号
{
if(ch==')'||ch=='('||ch==']'||ch=='['||ch=='}'||ch=='{')
return true;
return false;
}
bool toCheck(stacks &s,char ch) //检查是否匹配栈顶括号
{
if(s.empty())
return false;
switch(ch)
{
case ')':
if(s.top()=='(')
return true;
return false;
case ']':
if(s.top()=='[')
return true;
return false;
case '}':
if(s.top()=='{')
return true;
return false;
default:
return false;
}
}
int main()
{
ios::sync_with_stdio(false);
string str;
while(getline(cin,str,'\n'))
{
stacks s;
bool mark=true;
int len=str.length();
for(int i=0;i<len;i++)
{
if(isBrackets(str[i]))
{
if(str[i]=='('||str[i]=='['||str[i]=='{') //左括号入栈
s.push(str[i]);
else if(toCheck(s,str[i])) //右括号如果与栈顶匹配则弹出栈顶左括号
s.pop();
else
{
mark=false; //否则就标记 说明括号不匹配
break;
}
}
}
if(s.empty()&&mark)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}