括号匹配
题目描述
输入一个由 ( 、) 、[ 、] 4 种字符构成的字符串,判断其中的括号是否匹配。是则输出 yes,否则输出 no 。
参考程序
#include <iostream>
#include <stack> //包含容器stack
#include <string>
using namespace std;
stack < char > p; //定义一个栈容器 p,存储char类型元素
string s;
int main(){
p.push('#'); //前面加一个“哨兵”,避免访问空栈
cin>>s;
for(int i=0;i<s.size();i++){
if(s[i]=='(' || s[i]=='[')
p.push(s[i]); //当前字符为左括号则进栈
else{ //当前字符为右括号
if(s[i]==')' && p.top()=='(' || s[i]==']' && p.top()=='[')
p.pop(); //与栈顶的左括号匹配成功,弹出栈顶
else{
cout<<"no"<<endl; //匹配失败,输出“no”并结束程序
return 0;
}
}
}
if(p.top()!='#')
cout<<"no"<<endl; //栈中还有多余的左括号,匹配失败,输出“no”
else cout<<"yes"<<endl; //全部匹配成功,输出“yes”
return 0;
}程序说明:
- 第 2 句头文件
<stack>。 - 第 5 行定义容器栈变量时,要指明元素的类型,也可以是程序员自定义的类型。