链接:https://www.nowcoder.com/questionTerminal/e06d50b938d24a2b8a2c14edebee5478?toCommentId=5426981
来源:牛客网
表达式求值
给出一个布尔表达式的字符串,比如:true or false and false,表达式只包含true,false,and和or,现在要对这个表达式进行布尔求值,计算结果为真时输出true、为假时输出false,不合法的表达时输出error(比如:true true)。表达式求值是注意and 的优先级比 or 要高,比如:true or false and false,等价于 true or (false and false),计算结果是 true。
输入描述:
输入第一行包含布尔表达式字符串s,s只包含true、false、and、or几个单词(不会出现其它的任何单词),且单词之间用空格分隔。 (1 ≤ |s| ≤ 103).
输出描述:
输出true、false或error,true表示布尔表达式计算为真,false表示布尔表达式计算为假,error表示一个不合法的表达式。
示例1
输入
and
输出
error
示例2
输入
true and false
输出
false
示例3
输入
true or false and false
输出
true
思路
这题和简单计算器很像,将or定义为较低的优先级,and定义为较高的优先级(类比+,-,*,/)。true为1,false为0,将中缀表达式转换为后缀表达式,进行计算。
代码
链接:https://www.nowcoder.com/questionTerminal/e06d50b938d24a2b8a2c14edebee5478?toCommentId=5426981
来源:牛客网
#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
#include<queue>
#include<map>
using namespace std;
queue<int> q;//后缀队列
stack<int> st;//比较符号栈
map<string,int> mp;//优先级
void check(string s)
{
string t="";
for(int i=0;i<s.size()+1;i++)
{
if(i==s.size()||s[i]==' ')
{
if(t=="true")
q.push(1);
else if(t=="false")
q.push(0);
else
{
if(!st.empty()&&st.top()<mp[t])
{
st.push(mp[t]);
}
else{
while(!st.empty()&&st.top()>=mp[t])
{
q.push(st.top());
st.pop();
}
st.push(mp[t]);
}
}
t="";
}
else{
t+=s[i];
}
}
while(!st.empty())
{
q.push(st.top());
st.pop();
}
}
int cul()
{
stack<int> num;
while(!q.empty())
{
int n=q.front();
if(n==1||n==0)
{
num.push(n);
}
else{
if(num.empty())
return 2;
int c2=num.top();
num.pop();
if(num.empty())
return 2;
int c1=num.top();
num.pop();
if(n==3)
{
if(c1==1||c2==1)
{
num.push(1);
}
else
{
num.push(0);
}
}
else
{
if(c1==1&&c2==1)
{
num.push(1);
}
else
{
num.push(0);
}
}
}
q.pop();
}
if(num.size()>1||num.empty())
{
return 2;
}
else{
return num.top();
}
}
int main()
{
mp["and"]=4;
mp["or"]=3;
string s;
getline(cin,s);
check(s);
int n=cul();
if(n==1)
cout<<"true"<<endl;
else if(n==0)
{
cout<<"false"<<endl;
}
else
{
cout<<"error"<<endl;
}
}