Acwing3693括号匹配

先上错误代码(数组实现的栈,不太好,有空我再修改)。

#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/JMnQricon-default.png?t=N6B9http://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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值