本文共 1016 字,大约阅读时间需要 3 分钟。
分析
本题与计算器那道题的区别在于表达式的形式。
本题是后缀表达式,不需要额外的处理,可以直接让两个数字出栈进行运算。 而计算器那道题是中缀表达式,需要对符号的优先级进行判断。C++ 代码
class Solution {public: stack stk1; // 只需一个数字栈即可 bool dg(char c) { // 判断是否为合法数字 return (c >= '0' && c <= '9'); } int getc(string c) { // 判断符号类型 if (c == "+") return 1; if (c == "-") return 2; if (c == "*") return 3; return 4; } int evalRPN(vector &s) { int n = s.size(); for (int i = 0; i < n; ++i) { if (dg(s[i][0]) || (s[i].size() > 1 && s[i][0] == '-')) { // 数字或负数 stk1.push(stoi(s[i])); } else { // 运算符 int a = stk1.top(); stk1.pop(); int b = stk1.top(); stk1.pop(); int c = getc(s[i]); if (c == 1) b += a; if (c == 2) b -= a; if (c == 3) b *= a; if (c == 4) b /= a; stk1.push(b); } } return stk1.top(); // 结果在栈顶 }}; 转载地址:http://poag.baihongyu.com/