逆波兰表达式,情况不是很复杂,用一个栈就解决了。
#include <stack> #include <string> using namespace std; class Solution { public: int evalRPN(vector<string> &tokens) { for (int i = 0; i < tokens.size(); i++) { string &token = tokens[i]; if (token == "+") { int a = num_stack.top(); num_stack.pop(); int b = num_stack.top(); num_stack.pop(); int r = a + b; num_stack.push(r); } else if (token == "-") { int a = num_stack.top(); num_stack.pop(); int b = num_stack.top(); num_stack.pop(); int r = b - a; num_stack.push(r); } else if (token == "*") { int a = num_stack.top(); num_stack.pop(); int b = num_stack.top(); num_stack.pop(); int r = a * b; num_stack.push(r); } else if (token == "/") { int a = num_stack.top(); num_stack.pop(); int b = num_stack.top(); num_stack.pop(); int r = b / a; num_stack.push(r); } else { // number bool neg = (token[0] == '-'); int pos = 0; if (neg) { pos = 1; } int r = 0; for (int k = pos; k < token.length(); k++) { r = r * 10 + (token[k] - '0'); } if (neg) { r = -r; } num_stack.push(r); } } int result = num_stack.top(); num_stack.pop(); return result; } private: stack<int> num_stack; };
中间那些部分可以简化出来。
int o1, o2; o2 = numeric.top(); numeric.pop(); o1 = numeric.top(); numeric.pop(); switch(t[0]) { case '+': numeric.push(o1 + o2); break; case '-': numeric.push(o1 - o2); break; case '*': numeric.push(o1 * o2); break; case '/': numeric.push(o1 / o2); break; }
第二刷,Annie的解法比较简洁。且其中stoi可以直接将字符串转成整数。
python3,要注意//代表floor division
class Solution: def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token in ['+', '-', '*', '/']: num2 = stack.pop() num1 = stack.pop() if token == '+': stack.append(num1 + num2) elif token == '-': stack.append(num1 - num2) elif token == '*': stack.append(num1 * num2) elif token == '/': stack.append(int(num1 / num2)) else: stack.append(int(token)) return stack.pop()