数据结构实验之栈与队列四:括号匹配

roblem Description

 给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。

Input

 输入数据有多组,处理到文件结束。

Output

 如果匹配就输出“yes”,不匹配输出“no”

Sample Input

sin(20+10)
{[}]

Sample Output

yes
no

解决方案:遇到左括号,直接进栈,其他字符直接省略,

                遇到右括号,如果栈顶元素正好匹配,则使栈顶出栈,其他的直接跳出循环。

注意点:一开始的时候卡了,一直WA,没搞清楚cin和gets的用法,以后要注意。

使用cin时,>> 是会过滤掉不可见的字符(如 空格 回车,TAB 等),

cin>>noskipws>>input[j];//不想略过空白字符,那就使用 noskipws 流控制

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

# define maxSize 100
typedef char elem;
typedef struct node
{
    elem *top,*base;
    int stackSize;
}_sta;

void Init(_sta &s)
{
    s.base = (elem *)malloc(maxSize *sizeof(elem));
    if(!s.base) exit(-1);
    else s.top = s.base;
    s.stackSize = maxSize;
}

void push(_sta &s,elem k)
{
    if(s.top - s.base >= s.stackSize){
        s.base = (elem *)realloc(s.base,(maxSize + 10)*sizeof(elem));
        if(!s.base) exit(-1); //分配失败
        s.stackSize += 10;
    }
    *s.top++ = k;
}

elem pop(_sta &s)
{
    elem k;
    if(s.top == s.base) return 0;

    k = *(--s.top);
    return k;
}

elem top(_sta &s)
{
    elem k;
    if(s.top == s.base) return 0;
    k = *(s.top - 1);
    return k;
}

bool IsEmpty(_sta &s)
{
    if(s.base == s.top) return true;
    else return false;
}

int main()
{
    
    char str[110];
    //while(cin>>str){ //这里不能用cin,会省略空格
    while(gets(str)){
        _sta l;
        Init(l);
        int i;
        int len = strlen(str);
        for(i=0;i<len;i++){
            if(str[i] == '('||str[i] == '['||str[i] == '{'){
                push(l,str[i]);
            }
            else if(str[i] == ')'||str[i] == ']'||str[i] == '}'){
                if(IsEmpty(l)) break;
                else {
                    if((top(l) == '('&&str[i] == ')')||(top(l) == '['&&str[i] == ']')||(top(l) == '{'&&str[i] == '}')){
                        pop(l);
                    }
                    else break;
                }
            }
        }
        if(IsEmpty(l)&&i == len) 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、付费专栏及课程。

余额充值