题目描述
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中的字符串可能为空串,我在判断是否是数字还是运算符的时候直接使用isdigit(tokens[i][0])导致发生段错误;
(二)题目可以是负数,我没有考虑到,看了讨论区使用了字符串流,很是巧妙
这是我的错误代码:
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
int num = 0;
for (int i = 0; i < tokens.size(); i++) {
if (isdigit(tokens[i][0])) {
num = 0;
for (int j = 0; j < tokens[i].size(); j++) {
num = num * 10 + tokens[i][j] - '0';
}
st.push(num);
//cout << num << endl;
}
else {
int right = st.top();
st.pop();
int left = st.top();
st.pop();
if (tokens[i] == "+")
st.push(right + left);
else if (tokens[i] == "-")
st.push(left - right);
else if (tokens[i] == "*")
st.push(left * right);
else if (tokens[i] == "/")
st.push(left / right);
//cout << "***" << st.top() << endl;
}
}
return st.top();
}
};
更改后的正确代码:
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> st;
for (int i = 0; i < tokens.size(); i++) {
if ((tokens[i] == "+") || tokens[i] == "-" || tokens[i] == "*"
|| tokens[i] == "/") {
int right = st.top();
st.pop();
int left = st.top();
st.pop();
if (tokens[i] == "+")
st.push(right + left);
else if (tokens[i] == "-")
st.push(left - right);
else if (tokens[i] == "*")
st.push(left * right);
else if (tokens[i] == "/")
st.push(left / right);
//cout << "***" << st.top() << endl;
}
else {
stringstream ss;
ss<<tokens[i];
int temp;
ss>>temp;
st.push(temp);
}
}
return st.top();
}
};
这里提供字符串转整数的方法总结:
- int integer = atoi(str.c_str()); //使用cstdlib/stdlib.h库中的atoi函数
- stoi(str, nullptr, 10); //仅适用于c++11及其之后的编译器,后两个参数可以不用,默认转换为10进制,可以设定最后一个参数进行控制
- stringstream ss;
ss << str;
int integer;
ss >> integer;