本文共 1537 字,大约阅读时间需要 5 分钟。
逆波兰表示法(后缀表达式)是一种不需要括号的运算符序列表示方法,其优点是可以通过栈来高效地计算表达式的值。以下是解决这个问题的详细步骤:
#include#include #include using namespace std;bool isNumber(string &str) { return !(str == "+" || str == "-" || str == "*" || str == "/");}int evalRPN(vector tokens) { stack res; int n = tokens.size(); for (int i = 0; i < n; ++i) { string token = tokens[i]; if (isNumber(token)) { res.push(atoi(token.c_str())); } else { int b = res.top(); res.pop(); int a = res.top(); res.pop(); char op = token[0]; switch(op) { case '+': res.push(a + b); break; case '-': res.push(a - b); break; case '*': res.push(a * b); break; case '/': res.push(a / b); break; } } } return res.top();}
res
,用于保存中间结果。这种方法使用栈来模拟计算过程,时间复杂度为O(N),空间复杂度为O(N),适合处理逆波兰表达式的有效计算。
转载地址:http://txhu.baihongyu.com/