题目
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
分析
后缀表达式的简单计算。
数字暂时保存到栈中,从vector取到操作符后,从栈中取2个数字,进行计算,后再保存到栈中。
注意:
1、字符串转换为整数,负数的处理。
2、运算为整数运算。
时间复杂度
一次遍历,O(n)。
输入
vector<string> s1{"2", "1", "+"};
vector<string> s2{"2", "1", "+", "3", "*"};
vector<string> s3{"4", "13", "5", "/", "+"};
vector<string> s4{"3","-4","+"};
结论
运行时间:12ms。
CODE
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include <cstring>
#include <stdexcept>
#include <stack>
using namespace std;
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> sta;
for (auto s : tokens) {
if (!isOp(s)) {
// s is number
// push it into stack
sta.push(stringToInt(s));
} else {
// s is op
// take two number from stack
// calculate and then push into the stack
int val1, val2;
val2 = sta.top();
sta.pop();
val1 = sta.top();
sta.pop();
int res = calc(val1, val2, s);
sta.push(res);
}
}
return sta.top();
}
bool isOp(string s) {
if (s == "+" || s == "-" || s == "*" || s == "/") {
return true;
} else {
return false;
}
}
int calc(int v1, int v2, string op) {
if (op == "+") {
return v1 + v2;
} else if (op == "-") {
return v1 - v2;
} else if (op == "*") {
return v1 * v2;
} else if (op == "/") {
return v1 / v2;
} else {
cerr << "Operator is not right: " << op << endl;
}
}
int stringToInt(string s) {
// Caution: negative numbers
int val = 0, flag = 1;
int start = 0;
if (s[0] == '-') {
flag = -1;
start = 1;
}
for (int i = start; i < s.size(); ++i) {
val = val * 10 + s[i] - '0';
}
return flag * val;
}
};
int main()
{
vector<string> s1{"2", "1", "+"};
vector<string> s2{"2", "1", "+", "3", "*"};
vector<string> s3{"4", "13", "5", "/", "+"};
vector<string> s4{"3","-4","+"};
Solution so;
cout << so.evalRPN(s1) << endl;
cout << so.evalRPN(s2) << endl;
cout << so.evalRPN(s3) << endl;
cout << so.evalRPN(s4) << endl;
return 0;
}
356

被折叠的 条评论
为什么被折叠?



