给定仅包含“()[]{}”六种括号的字符串,请你判断该字符串中,括号的匹配是否是合法的,也就是对应括号的数量、嵌套顺序完全正确。
输入格式:
第一行一个整数T(T<=10)
其后T行每行一个字符串只包含[{()}]六种字符(字符串长度2e5以内)
输出格式:
对于每个字符串,匹配输出Yes,否则输出No
输入样例:
2
{()[]}
([)]
输出样例:Yes
No
THE FIRST
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
int T;
cin>>T;
string temp;
stack<char> s1;
int count = 0;
while(T--)
{
cin>>temp;
for(int i = 0; i <temp.size(); i++)
{
if(temp[i] == '{' || temp[i] == '[' || temp[i] == '(')
{s1.push(temp[i]);
}else
if(temp[i] == '}')
{
if(s1.top()=='{') s1.pop();
else
{
count = 1;
break;
}
}else
if(temp[i] == ']')
{
if(s1.top()=='[') s1.pop();
else
{
count = 1;
break;
}
}else
if(temp[i] == ')')
{
if(s1.top() == '(' )s1.pop();
else
{
count = 1;
break;
}
}
if(s1.empty() )
break;
}
if(count == 1) cout<<"No"<<endl;
else cout<<"Yes"<<endl;
}
return 0;
}
1.刚开始temp的数据类型是string,stack也是string,但需要一个个比较括号,就相当于是字符串与字符之间比较,‘【’是字符,虽然编译没有错误,但结果都是yes。因此temp的数据类型还是string,但stack的数据类型改为char,然后用temp[i]读取字符(将temp看作vector使用)。
2.显示段错误,stack为空时,无法比较
3.第二次把empty移到前面,先判断stack是不是空在用右括号比较左括号,这次又忘记每次循环后吧count清零了,最近老是忘记清零。
4.第三次只有一个答案不对,到底是什么啊,是这个”[]{“,
5.the last: I forgot clear stack;
这种不知到循环多少次还用到数组的程序,根据需要考虑是否在循环末尾编写clear()函数
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
int T;
cin>>T;
string temp;
stack<char> s1;
int count = 0;
while(T--)
{
count = 0;
cin>>temp;
// cout<<temp.size()<<endl;
for( unsigned int i = 0; i <temp.size(); i++)
{
if(temp[i] == '{' || temp[i] == '[' || temp[i] == '(')
{
s1.push(temp[i]);
// cout<<i<<':'<<temp[i]<<endl;
continue;
// cout<<i<<endl;
}else
if(s1.empty())
{
count = 1;
break;
}
// cout<<i<<':'<<temp[i]<<endl;
if(temp[i] == '}')
{
if(s1.top()=='{') s1.pop();
else
{
count = 1;
break;
}
}else
if(temp[i] == ']')
{
if(s1.top()=='[') s1.pop();
else
{
count = 1;
break;
}
}else
if(temp[i] == ')')
{
if(s1.top() == '(' )s1.pop();
else
{
count = 1;
break;
}
}
}
if(!s1.empty())
{
count = 1;
// break;
}
if(count == 1) cout<<"No"<<endl;
if(count == 0)cout<<"Yes"<<endl;
while(!s1.empty())
{
s1.pop();
}
}
return 0;
}