LeetCode 150. Evaluate Reverse Polish Notation 辅助数据结构栈

来源:互联网 发布:usb编程器 编辑:程序博客网 时间:2024/06/14 15:00

    • 题目
      • 题意
      • 注意
      • 思路
      • 代码
      • 结果

题目

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 evalRPN(vector<string>& tokens) {        stack<int> sta;        int calc = 0;  //只有整型的计算,不涉及浮点型        int s1 = 0, s2 = 0;        for (int i = 0; i < tokens.size(); i++)        {            string s = tokens[i];            if (s == "+")            {                s2 = sta.top();                sta.pop();                s1 = sta.top();                sta.pop();                calc = s1 + s2;                sta.push(calc);            }             else if (s == "-")            {                s2 = sta.top();                sta.pop();                s1 = sta.top();                sta.pop();                calc = s1 - s2;                sta.push(calc);            }            else if (s == "*")            {                s2 = sta.top();                sta.pop();                s1 = sta.top();                sta.pop();                calc = s1 * s2;                sta.push(calc);            }            else if (s == "/")            {                s2 = sta.top();                sta.pop();                s1 = sta.top();                sta.pop();                calc = s1 / s2;                sta.push(calc);            }            else            {                sta.push(stoi(s));  //stoi 字符串转整型            }        }        return sta.top();   //注意这个条件,最终是将结果放在了栈中    }};

结果

这里写图片描述

阅读全文
0 0
原创粉丝点击