洛谷 P1739 表达式括号匹配【STL/stack/模拟】

题目描述
假设一个表达式有英文字母(小写)、运算符(+,—,*,/)和左右小(圆)括号构成,以“@”作为表达式的结束符。请编写一个程序检查表达式中的左右圆括号是否匹配,若匹配,则返回“YES”;否则返回“NO”。表达式长度小于255,左圆括号少于20个。

输入输出格式
输入格式:
一行:表达式

输出格式:
一行:“YES” 或“NO”

输入输出样例
输入样例#1:
2*(x+y)/(1-x)@

输出样例#1:
YES
输入样例#2:
(25+x)(a(a+b+b)@
输出样例#2:
NO
说明
表达式长度小于255,左圆括号少于20个

【STL】

#include<algorithm>
#include<cstdio>
#include<iostream>
#include<set>
#include<sstream>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<cstring>
#include<string.h>
using namespace std;
const int maxn = 1e5+5;
char s[maxn];
stack<char> st;
int main()
{
    cin>>s;
    for(int i=0; s[i]!='@'; i++)
    {
        if(s[i]=='(') st.push(s[i]);
        if(s[i]==')'){
            if(st.empty()){
                cout<<"NO"<<endl;
                return 0;
            }
            else st.pop();
        }
    }
    if(!st.empty()) printf("NO\n");
    else printf("YES\n");
    return 0;
}

【数组模拟】

#include<algorithm>
#include<cstdio>
#include<iostream>
#include<set>
#include<sstream>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<string>
#include<cstring>
#include<string.h>
using namespace std;
const int maxn = 1e5+5;
char s[maxn];
stack<char> st;
int main()
{
    int top=0;
    cin>>s;
    for(int i=0; s[i]!='@'; i++)
    {
        if(s[i]=='(') top++;
        if(s[i]==')'){
            if(top) top--;
            else {cout<<"NO"<<endl;return 0;}
        }
    }
    if(top) printf("NO\n");
    else printf("YES\n");
    return 0;
}

转载于:https://www.cnblogs.com/Roni-i/p/9070040.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值