NYOJ 2 括号匹配问题

时间:2022-08-19 18:52:48
//RuntimeError
#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
using namespace std;

stack<char>s;

int main()
{
int n;
cin>>n;
while(n--)
{
string expr;
cin>>expr;
int len=expr.length();
for(int i=0;i<len;i++)
{
if((expr[i]=='(') || (expr[i]=='['))
s.push(expr[i]);
else if(expr[i]==')' )
{
if(s.top()=='(')
s.pop();
else
s.push(expr[i]);
}
else if(expr[i]==']')
{
if(s.top()=='[')
s.pop();
else
s.push(expr[i]);
}
}
if(s.empty())
printf("Yes\n");
else
printf("No\n");
while(!s.empty())
s.pop();
}
return 0;
}
//为啥最后不能直接用 栈不空就弹出呢?感觉可能与栈的非法访问有关
//AC代码
#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
using namespace std;

stack<char>s;

int main()
{
int n;
s.push('#');
cin>>n;
while(n--)
{
string expr;
cin>>expr;
int len=expr.length();
for(int i=0;i<len;i++)
{
if((expr[i]=='(') || (expr[i]=='['))
s.push(expr[i]);
else if(expr[i]==')' )
{
if(s.top()=='(')
s.pop();
else
s.push(expr[i]);
}
else if(expr[i]==']')
{
if(s.top()=='[')
s.pop();
else
s.push(expr[i]);
}
}
if(s.top()=='#')
printf("Yes\n");
else
printf("No\n");
while(s.top()!='#')
s.pop();
}
return 0;
}