输入:tokens = ["2","1","+","3","*"] 输出:9 解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
思想:用栈。
ps:思想很简单。实际中犯的错误非常多。
1.先开始想的是遍历tokens,用isdigit()函数先判断该元素是否为数字,但是问题是,isdigit()函数只能判断一个字符,不能判断一个字符串,所以我采用isdigit(tokens[i][0])来判断,即判断每个字符串元素的第一个字符是否为数字。但是!!!当字符串是负数如"-11"时会发生什么。
2.判断是否为运算符时,如tokens[i] == "+",不要用tokens[i] == '+',这是错的,左边是字符串,右边是字符。c++的单引号和双引号是有区别的,一个是字符,一个是字符串(python写多了,就乱用了)。也不要用tokens[i][0] == '+'(好像某些情况会出错,具体原因忘了,写代码的时候发现的)。
3.运算的时候注意a、b的顺序,第一个出来的在后,第二个出来的在前。
代码:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
//["2", "1", "+", "3", " * "]
//vector<string> tokens = { "10","6","9","3","+","-11","*","/","*","17","+","5","+" };
for (int i = 0;i < tokens.size();i++) {
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
int b = st.top();
st.pop();
int a = st.top();
st.pop();
if (tokens[i] == "+")
st.push(a + b);
if (tokens[i] == "-")
st.push(a - b);
if (tokens[i] == "*")
st.push(a * b);
if (tokens[i] == "/")
st.push(a / b);
}
else {
st.push(stoi(tokens[i]));
}
}
//cout << st.top()<<endl;
return st.top();
}
};
第一版错误代码:
int main()
{
stack<int> st;
//["2", "1", "+", "3", " * "]
vector<string> tokens = { "10","6","9","3","+","-11","*","/","*","17","+","5","+" };
for (int i = 0;i < tokens.size();i++) {
//cout << tokens[i] << endl;
if (isdigit(tokens[i][0])) {
cout << tokens[i] << endl;
st.push(stoi(tokens[i]));
}
else {
int b = st.top();
//cout << b << endl;
st.pop();
int a = st.top();
st.pop();
int c;
if (tokens[i] == "+") {
c = a + b;
}
else if (tokens[i] == "-") {
c = a - b;
}
else if (tokens[i] == "*") {
c = a * b;
}
else if (tokens[i] == "/") {
c = a / b;
}
st.push(c);
}
}
//cout << st.top() << endl;
return st.top();
}