给定三种括号{ },[ ], ( ),和若干小写字母的字符串,请问改字符串的括号是否匹配(可以嵌套)?
输入输出
输入格式:字符串s。 输出格式:若匹配,输出yes,否则输出no。
输入样例
{[a(v)d]q}
输出样例
yes
解题思路:
(1)运用容器栈来分析;
(2)遇到左括号,压入栈中,遇到右括号,判断是否与栈顶元素匹配,匹配则删除栈顶元素;
(3)最后判断栈是否为空,空则输出yes,否则no;
代码:
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main(){
string str;
stack<char> st;
getline(cin,str);
for(int i=0;i<str.size();i++){
if(str[i]=='{'||str[i]=='['||str[i]=='('){
st.push(str[i]);//左括号压入栈中
}else if(str[i]=='}'||str[i]==']'||str[i]==')'){
if(str[i]=='}'&&st.top()=='{'||str[i]==')'&&st.top()=='('||str[i]==']'&&st.top()=='['){
st.pop(); //删除栈顶元素
}else{
cout<<"no"<<endl;
return 0;
}
}else continue;
}
if(st.empty()) cout<<"yes"<<endl; //栈为空
else cout<<"no"<<endl; //栈不为空
return 0;
}