先上错误代码(数组实现的栈,不太好,有空我再修改)。
#include <iostream>
#include <string>
#
using namespace std;
const int N=100010;
char shuzu[N];
/*编程之前要静下心来去写一遍算法
第一步 字符检验
第二步 左则压入
第三步 右则对比
*/
int main()
{ string str;
cin>>str;
int j=0;
int tag=0;//这里tag=0时默认为不匹配 tag=1为匹配
for(int i=0;i<str.length();i++)//注意str使用时需要导入#include <string>,而且使用方法是str.length();
{
if(str[i]=='<'||str[i]=='('||str[i]=='{'||str[i]=='[')
{
shuzu[j]=str[i];
j++;
}
else
{
if(shuzu[j]=='('&&str[i]==')'||shuzu[j]=='<'&&str[i]=='>'||shuzu[j]=='{'&&str[i]=='}'||shuzu[j]=='['&&str[i]==']')//问题出在这了 如果是(,那则么说明)才是匹配呢 多写几个吧还是
{
tag=1;
shuzu[j]='0';
j--;
} else
{
tag=0;
break;
}
}
}
//第一次调试 不管输入什么 都显示no
if(tag)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
括号匹配这个题,用到了#include<stack>,这个库,所以我们先找一篇博客进行学习。
http://t.csdn.cn/JMnQrhttp://t.csdn.cn/JMnQr这个写的真不错的。
接下来是自己看题解复现的代码,没有计算时间。只用了字符串和栈。
等学了哈希再用哈希试试
AC代码如下 很简单
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
stack <char> zifu;
string chuan;
cin>>chuan;
for(int i=0;i<chuan.length();i++)
{
if(chuan[i]=='<'||chuan[i]=='('||chuan[i]=='{'||chuan[i]=='[')
zifu.push(chuan[i]);
else
{
if(zifu.empty())
{
cout<<"no"<<endl;
return 0;
}
if((chuan[i]==']'&&zifu.top()=='[')||(chuan[i]=='}'&&zifu.top()=='{')||(chuan[i]==')'&&zifu.top()=='(')||(chuan[i]=='>'&&zifu.top()=='<'))
zifu.pop();
}
}
if(zifu.empty())
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
return 0;
}