首页 > 其他 > 详细

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

时间:2018-05-22 00:41:28      阅读:307      评论:0      收藏:0      [点我收藏+]

题目描述
假设一个表达式有英文字母(小写)、运算符(+,—,*,/)和左右小(圆)括号构成,以“@”作为表达式的结束符。请编写一个程序检查表达式中的左右圆括号是否匹配,若匹配,则返回“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;
}

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

原文:https://www.cnblogs.com/Roni-i/p/9070040.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!