150. 逆波兰表达式求值

题目描述

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

逆波兰式(Reverse Polish notation,RPN,或逆波兰记法),也叫后缀表达式(将运算符写在操作数之后)

思路

从左到右将表达式的元素放入栈中,遇到运算符时,从栈中取出两个元素进行这个运算,将运算结果放入栈中,继续对表达式进行扫描。

代码实现

class Solution {
public:
    int evalRPN(vector<string> &tokens) 
    {   

    	stack<int> s;
      //流式处理
    	for(auto iter = tokens.begin();iter!=tokens.end();iter++)
    	{
    		string str = *iter;
    		if(str == "+" || str == "-" || str == "*" || str == "/")
    		{
		   int two = s.top();
		   s.pop();
		   int one = s.top();//注意这里的操作数顺序不要搞反了
		   s.pop();
		   int ret = 0;
		   if(str == "+")
			ret = one + two;
		   if(str == "-")
			ret = one - two;
		   if(str == "*")
			ret = one * two;
		   if(str == "/")
			ret = one / two;
		   s.push(ret);//抽象出来的公共操作
    		}
    		else
	            s.push(atoi(str.c_str()));//c_str()将std::string转化为标准C风格字符串    		
    	}
    return s.top();    	
    }
};

posted on 2021-05-02 14:46  朴素贝叶斯  阅读(35)  评论(0编辑  收藏  举报

导航