算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+
、-
、*
、\
以及左右括号()
,表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
解题思路:
这道题比较混蛋,很混蛋,他也咩有告诉你到底是什么数字,而且还把“/”给打反了打成了“\”,其次呢,对于数字的输入不只是一位整数,而是:正负都有的多位小数输入 。骗子,曰噢。
我的处理办法是用string::iterator来记录当前扫描到的位置,然后用这个iterator来进行数字的单独识别,其他情况按照逆波兰算法处理就好,其他博主的文章写的已经很多了,原理就不再赘述了,此处留下博主的一种实现方案。
代码:
#include <iostream>
#include <map>
#include <stack>
#include <vector>
using namespace std;
typedef map<char, int> TokenLevel;
vector<string> reversePolishNotation(const string& expression, const TokenLevel& tokenLevel);
string readNumber(string::const_iterator& it, const string& expression);
int main() {
const TokenLevel tokenLevel{
{'+', 1},{'-', 1},
{'*', 2},{'/', 2},
{'(', 0},{')', 0}
};
string inputExpression;
cin >> inputExpression;
auto res = reversePolishNotation(inputExpression, tokenLevel);
cout << res[0];
for (int i = 1; i < res.size(); i++) {
cout << " " << res[i];
}
return 0;
}
inline bool checkNumber(string::const_iterator& it, const string& expression) {
return isdigit(*it) ||
(it == expression.begin() || *(it - 1) == '(') && (*it == '-' || *it == '+') ||
*it == '.' && isdigit(*(it + 1));
}
string readNumber(string::const_iterator& it, const string& expression) {
string rtn;
while (it != expression.end() && checkNumber(it, expression))
if (*it != '+') rtn += *it++; else ++it;
return rtn;
}
vector<string> reversePolishNotation(const string& expression, const TokenLevel& tokenLevel) {
vector<string> result;
vector<char> buffer;
for (auto it = expression.begin(); it != expression.end();) {
auto ch = *it;
if (!checkNumber(it, expression)) {
if (ch == '(' || buffer.empty()) {
buffer.push_back(ch);
} else if (ch == ')') {
while (buffer.back() != '(') {
result.push_back(string{ buffer.back() });
buffer.pop_back();
}
buffer.pop_back();
} else {
if (tokenLevel.at(ch) <= tokenLevel.at(buffer.back())) {
while (!buffer.empty() && tokenLevel.at(ch) <= tokenLevel.at(buffer.back())) {
result.push_back(string{ buffer.back() });
buffer.pop_back();
}
}
buffer.push_back(ch);
}++it;
} else result.push_back(readNumber(it, expression));
}
while (!buffer.empty()) {
result.push_back(string{ buffer.back() });
buffer.pop_back();
}
return result;
}
当然,博主为什么这么写呢,当然是为了可读性和可维护性还有可扩展性啦。
举个🌰
将
inline bool checkNumber(string::const_iterator& it, const string& expression);
中的isdigit数字判定改为isalnum之后,就可以解析单词啦o(* ̄▽ ̄*)ブ
inline bool checkNumber(string::const_iterator& it, const string& expression) {
return isalnum(*it) ||
(it == expression.begin() || *(it - 1) == '(') && (*it == '-' || *it == '+') ||
*it == '.' && isalnum(*(it + 1));
}
测试
结尾:
(´▽`ʃ♡ƪ) over~
就这。