LeetCode150—Evaluate Reverse Polish Notation

来源:互联网 发布:mac版finale怎么激活 编辑:程序博客网 时间:2024/06/06 19: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


分析

逆波兰表达式求解,看通过率不高本以为会有浮点数,后来custom测试一下发现表达式中求解结果为整型。

表达式中的操作符和操作数都是以string的形式呈现,所以整个逆波兰式保存在vector中。逆波兰式的求解办法是很简单的,用一个stack实现。

本题需要注意的有两点:

1.string 转 int

c风格的代码可以这样写:

string s="123";atoi(s.c_str());

不过推荐C++11的做法

string s="123";std::stoi(s);

2.负数与减操作符的区分

第一次提交没过就是这个原因,想了一个办法,从vector中取出的string要么是操作符要么是操作数,操作符的size肯定是1,在这个前提下如果该string的第一个字符是’+’ 、’-‘、 ‘*’、 ‘/’那么该string就被判定为操作符。

3.代码

class Solution {public:    int evalRPN(vector<string>& tokens) {        stack<int>s;        for (int i = 0; i < tokens.size(); i++)        {        //第一个条件为了区分负数            if ((tokens[i].size()==1)&&(tokens[i][0] == '+' || tokens[i][0] == '*' || tokens[i][0] == '/' || tokens[i][0] == '-'))            {                char op = tokens[i][0];                int second = s.top();                s.pop();                int first = s.top();                s.pop();                switch (op){                case '+':                    s.push(first + second);                    break;                case '-':                    s.push(first - second);                    break;                case '*':                    s.push(first * second);                    break;                case '/':                    s.push(first / second);                    break;                default:                    break;                }            }            else            {                s.push(stoi(tokens[i]));            }        }        return s.top();    }};
1 0
原创粉丝点击