[Leetcode] Evaluate Reverse Polish Notation

时间:2014-06-07 20:34:41   收藏:0   阅读:214

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

思路:
设置stack<int>型的栈,遇到操作数就压入栈中,遇到操作符就从栈中取出2个数进行运算,并把运算结果压入栈中进行下次运算。

注意:
(1) 因为要把运算结果压入栈中,所以栈应存放int型值,不能设计成存放string型的。
(2) 把string转化成int用atoi函数,atoi函数的原型int atoi(const char *nptr);
具体
int Strtoi(string str)
{
    const char *s = &str[0];    
    return atoi(s);
}


       或者

int Strtoi(string str)
{    
    return atoi(str.c_str());//c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同. 
}


设计程序时特殊情况考虑
vector<string>中只存在一个值没有操作符,那么就没有进行运算,所以程序中函数evalRPN()的返回值不能是result,应该是压入栈中的操作数,
因为即使是进行了运算符操作,其操作结果也会压入栈中。
 


bubuko.com,布布扣
int Strtoi(string str)
{
    const char *s = &str[0];
    
    return atoi(s);


}

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        
        stack<int> operand;
        int result;
        for(vector<string>::iterator iter= tokens.begin();iter != tokens.end();iter++)
        {
            if( (*iter)=="+" ||(*iter)=="-" ||(*iter)=="*" ||(*iter)=="/" )//有可能vector里只有一个数没有操作符,直接只执行else,则result没有值
            {
                int B = operand.top();
                operand.pop();
                int A = operand.top();
                operand.pop();
                
                if(*iter == "+")
                   result = A+B;
                else if(*iter == "-")
                   result = A-B;
                else if(*iter == "*")
                   result = A*B;
                else 
                   result = A/B;

                operand.push(result);
            
            }
            else
            {
              int ope = Strtoi(*iter);
              operand.push(ope);
            }
        
        }
        return operand.top(); //返回值不能是result,有可能是vector里唯一的数值(被压入栈里了)
    }
};
bubuko.com,布布扣

 

[Leetcode] Evaluate Reverse Polish Notation,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!