数据结构实验之栈四:括号匹配
来源:互联网 发布:ubuntu selinux 状态 编辑:程序博客网 时间:2024/06/06 00:05
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
题解:这个题首先应该判断出现的第一个括号是不是右括号,是则结束循环,不是你就将左括号入栈,然后和出现的右括号作比较,匹配则栈顶出栈,否则结束循环
输入
输入数据有多组,处理到文件结束。
输出#include<iostream>#include<stack>#include<cstring>#include<cstdio>using namespace std;int cop(char x){ if(x=='('||x==')') return 1; if(x=='}'||x=='{') return 2; if(x=='['||x==']') return 3;}int main(){ char ch[60]; int i; stack<char> st; while(gets(ch)!=NULL) { int len=strlen(ch); int flag=0; for(i=0; i<len; i++) { if(st.empty()&&(ch[i]=='}'||ch[i]==']'||ch[i]==')')) { flag=1; break; } else if(ch[i]=='{'||ch[i]=='['||ch[i]=='(') { st.push(ch[i]); } else if(ch[i]=='}'||ch[i]==']'||ch[i]==')') { if(cop(st.top())==cop(ch[i])) st.pop(); else { flag=1; break; } } } if(!flag&&st.empty()) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0;}
如果匹配就输出“yes”,不匹配输出“no”
示例输入
sin(20+10){[}]
示例输出
yesno
0 0
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- 数据结构实验之栈四:括号匹配
- HD--1285 确定比赛名次
- 判断子串
- memcache原理
- osg入门答疑
- 关于Mac系统升级到10.11.x之后cocoapods不能使用问题
- 数据结构实验之栈四:括号匹配
- linphone-PayloadTypeImpl文件对应的JNI层文件分析
- JVM调优总结(这个总结得比较全面)
- 顺序表应用1:多余元素删除之移位算法
- 消息队列
- android之layout_toLeftOf和layout_toRightOf出现的错误
- 操作系统--Linux学习
- 搭建Jenkins+Github集成环境
- Linux下的C语言学习笔记(1)