LeetCode 150 逆波兰表达式求值

2019-10-31  本文已影响0人  萨缪

150. 逆波兰表达式求值

思路就是主要用到一个 string类转浮点型的函数 stringstream 还有一个栈,同时对数组中的每一个单元进行判断,如果是纯数字,则直接运用那个函数转换成数字,如果是符号,则进行运算(其中带有入栈和出栈)
但要注意,验证其是否为符号是要用 ""双引号! 因为stirng是字符串类型 不能用 '' 单引号

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> a;
        for (int i = 0; i < tokens.size(); i++) {
            int num = 0;
            //只有单个数字时 转换成浮点数
            if (tokens[i] != "+" || tokens[i] != "-" || tokens[i] != "*" || tokens[i] != "/") {
                num = 0;
                stringstream s;
                s << tokens[i];
                s >> num;
            }
            if (tokens[i] == "+") {
                int m = a.top();
                a.pop();
                int n = a.top();
                a.pop();
                a.push(m+n);
            } else if (tokens[i] == "-") {
                int m = a.top();
                a.pop();
                int n = a.top();
                a.pop();
                a.push(n-m);
            } else if (tokens[i] == "*") {
                int m = a.top();
                a.pop();
                int n = a.top();
                a.pop();
                a.push(m*n);
            } else if (tokens[i] == "/") {
                int m = a.top();
                a.pop();
                int n = a.top();
                a.pop();
                a.push(n/m);
            } else {
                num = 0;
                stringstream s;
                s << tokens[i];
                s >> num;
                a.push(num);
            }
        }
        return a.top();
    }
};
上一篇 下一篇

猜你喜欢

热点阅读