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

2023-06-12,,

题目描述

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

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

下载本文的Word格式文档,以方便收藏与打印。