[LeetCode]Evaluate Reverse Polish Notation

来源:互联网 发布:中国蓝tv网络直播 编辑:程序博客网 时间:2024/04/30 13:21

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

class Solution { public:    int stringToDigit(std::string s){bool state = true;int ans = 0;int multi = 1;for (int i = 0; i < s.size(); i++){if (s[i]=='-'){state = false;}else {multi = 10;ans = multi * ans + s[i] - '0';}}if (!state){return -ans;}return ans;}int evalRPN(std::vector<std::string> &tokens) {std::vector<int> rct;for (int i = 0; i < tokens.size(); i++){int temp;if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/"){temp = stringToDigit(tokens[i]);rct.push_back(temp);//temp2 = stringToDigit(tokens[i]);}else if (tokens[i] == "+"){int temp1 = rct[rct.size() - 1];rct.pop_back();int temp2 = rct[rct.size() - 1];rct.pop_back();rct.push_back(temp2 + temp1);}else if (tokens[i] == "-"){int temp1 = rct[rct.size() - 1];rct.pop_back();int temp2 = rct[rct.size() - 1];rct.pop_back();rct.push_back(temp2 - temp1);}else if (tokens[i] == "*"){int temp1 = rct[rct.size() - 1];rct.pop_back();int temp2 = rct[rct.size() - 1];rct.pop_back();rct.push_back(temp2 * temp1);}else if (tokens[i] == "/"){int temp1 = rct[rct.size() - 1];rct.pop_back();int temp2 = rct[rct.size() - 1];rct.pop_back();rct.push_back(temp2 / temp1);}else{;}}return rct[0];}};

网上找的此代码比较简洁,用到了一些函数:

class Solution {public:    int evalRPN(vector<string> &tokens) {        int a, b;        stack<int> s;        for(int i = 0; i < tokens.size(); i ++)        {            if(isdigit(tokens[i][0]) || tokens[i].length() > 1)            {                s.push(atoi(tokens[i].c_str()));                continue;            }            a = s.top();s.pop();            b = s.top();s.pop();            switch(tokens[i][0])            {                case '+': s.push(b + a); break;                case '-': s.push(b - a); break;                case '*': s.push(b * a); break;                case '/': s.push(b / a); break;            }        }        return s.top();    }};




0 0
原创粉丝点击