Evaluate Reverse Polish Notation

来源:互联网 发布:逆袭网络剧下载 编辑:程序博客网 时间:2024/04/28 13:55

https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/

考察知识点:栈


1、题目要求:计算逆波兰表达式的值。

逆波兰表达式又称后缀表达式,我们常见的是中缀表达式,即运算符在两个操作数之间,例"a + b * c - d / e",若将此中缀表达式转换成后缀表达式,则是"a b c * + d e / -"。

例:["2", "1", "+", "3", "*"]对应表达式"(2+1)*3",返回9;

["4", "13", "5", "/", "+"]对应表达式"4+13/5",返回6;


2、解题思路:

后缀表达式和计算机操作一致,从左至右依次读取逆波兰表达式,如果遇到操作数,则将其压入栈中,如果遇到操作符,则从栈中弹出两个操作数参与运算,并将计算结果压入栈中,然后读取下一个表达式字符。



class Solution {public:    int evalRPN(vector<string> &tokens)     {        stack<int> s1;    int t1, t2;    string temp;    int result;    for (vector<string>::const_iterator iter = tokens.begin(); iter != tokens.end(); iter++)    {    temp = *iter;    if (temp == "+" )                   //当遇到预算符时,弹出栈中的两个数进行计算,并将计算结果压入栈中    {    t1 = s1.top();    s1.pop();    t2 = s1.top();    s1.pop();    t2 = t2 + t1;    s1.push(t2);    }    else if (temp == "-")    {    t1 = s1.top();    s1.pop();    t2 = s1.top();    s1.pop();    t2 = t2 - t1;    s1.push(t2);    }    else if (temp == "*")    {    t1 = s1.top();    s1.pop();    t2 = s1.top();    s1.pop();    t2 = t2 * t1;    s1.push(t2);    }    else if (temp == "/")    {    t1 = s1.top();    s1.pop();    t2 = s1.top();    s1.pop();    t2 = t2 / t1;    s1.push(t2);    }    else                                //其他情况则将string型字符转换成int型压入栈中    {        stringstream ss(temp);          //利用stringstream流将string型转换成int型        int tempresult;        ss >> tempresult;                s1.push(tempresult);    }    }        result = 0;    if (!s1.empty())    result = s1.top();        return result;        }};


0 0