题目描述
PIPI现在有若干个包含小写英文字母作为操作数 以及 ‘+’, ‘-’, '’, ‘/’, ‘^’ 五种操作符的合法中缀表达式。请你将其转为后缀表达式(逆波兰式)。
输入
输入一个字符串s,表示中缀表达式。
输出
输出一个字符串表示对应的后缀表达式。
样例输入
a^b+cd/e-f
样例输出
ab^cd*e/+f-
反思
一开始自己写的时候分了很多种情况讨论,后来看了PIPI算法册子,解题思路用的是优先级。
第一次看到这样记录优先级的方法,晚上回来又码了一遍,心觉妙哉,遂记。
// 题目:中缀表达式转后缀表达式I
// 日期:2021/7/14
// 详情:有若干个包含小写英文字母作为操作数以及'+','-','*','/','^'五种操作符的合法中缀表达式。
// 请你将其转为后缀表达式(逆波兰式)。
// XWQ
#include <bits/stdc++.h>
using namespace std;
void Check(string str){
stack<char> op;
int priority[300];
priority['+'] = priority['-'] = 0; // 1.定义优先级
priority['*'] = priority['/'] = 1;
priority['^'] = 2;
for(int i=0; i<str.size(); i++){
if(str[i]>='a' && str[i]<='z'){
printf("%c", str[i]);
}
else{
if(op.empty()){
op.push(str[i]);
}
else{
while(!op.empty() && priority[str[i]]<=priority[op.top()]){ // 2.使用优先级比较
printf("%c", op.top());
op.pop();
}
op.push(str[i]);
}
}
}
while(!op.empty()){
printf("%c", op.top());
op.pop();
}
}
int main(){
string str;
cin >> str;
Check(str);
}