codeup 1982 Problem B 符号匹配

题目描述

请写一个程序,判断给定表达式中的括号是否匹配,表达式中的合法括号为”(“, “)”, “[", "]“, “{“, ”}”,这三个括号可以按照任意的次序嵌套使用。

输入
有多个表达式,输入数据的第一行是表达式的数目,每个表达式占一行。

输出
对每个表达式,若其中的括号是匹配的,则输出”yes”,否则输出”no”。
样例输入
4
[(d+f)*{}]
[(2+3))
()}
[4(6]7)9
样例输出
yes
no
no
no

思路

这道题只是判断符号是不是匹配,所以我们利用栈的知识,栈中只存括号,等到字符串遍历结束,通过栈是不是空来判断结果。
1.如果字符为"("、"["、"{",就入栈。
2.如果字符为")"、"]"、"}",就判断,若是栈为空,则入栈对应第3种情况;若栈不为空,则与栈顶元素匹配,若是匹配成功,栈顶元素出栈,否则该字符进栈,这里对应样例的第4种情况。
3.如果字符为其他,则跳过。
4.若栈为空,输出yes,否则输出no。然后清空栈

代码

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <stack>
using namespace std;
//匹配
bool match(char a,char b){
    if(a=='['&&b==']') return true;
    else if(a=='{'&&b=='}') return true;
    else if(a=='('&&b==')') return true;
    else return false;
}

int main(){
    int n;
    string str;
    stack<char> st;
    while(~scanf("%d",&n)){
        while(n--){
            cin>>str;
            int len=str.length();
            for(int i=0;i<len;i++){
                if(str[i]=='{'||str[i]=='['||str[i]=='('){
                    st.push(str[i]);//入栈
                }else if(str[i]=='}'||str[i]==']'||str[i]==')'){
                    if(st.empty()==false){//栈不为空
                        if(match(st.top(),str[i])==true){//匹配成功
                            st.pop();
                        }
                        else{//匹配失败
                            st.push(str[i]);
                        }
                    }else{//栈为空,直接入栈
                        st.push(str[i]);
                    }

                }else continue;
            }
            if(st.empty()==true) cout<<"yes"<<endl;//输出
            else cout<<"no"<<endl;
            while(st.empty()!=true){//清空栈,用于下一个字符串
                st.pop();
            }
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值