栈在括号匹配中的应用(非常基础)
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
int main()
{
string s;
stack<char> stk; //定义一个具有栈性质的字符数组
cin >> s;
for(auto it = s.begin();it != s.end();it++)
{
if(*it=='<' || *it == '(' || *it == '[' ||*it =='{')
stk.push(*it);//入栈操作
else
{
if(stk.size()==0)
{
cout << "no" << endl;
return 0;
}
if ((*it == '>' && stk.top() == '<') ||
(*it == ')' && stk.top() == '(') ||
(*it == ']' && stk.top() == '[') ||
(*it == '}' && stk.top() == '{') )
{
stk.pop(); //如果匹配则执行出栈操作
}
else
{
cout << "no" <<endl;
return 0; //防止出现segmation fault
}
}
}
if(stk.empty()==true) cout << "yes" << endl;
else cout << "no" << endl;
return 0;
}