zoukankan      html  css  js  c++  java
  • [Leetcode] Evaluate Reverse Polish Notation

    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,应该是压入栈中的操作数,
    因为即使是进行了运算符操作,其操作结果也会压入栈中。
     


    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里唯一的数值(被压入栈里了)
        }
    };
  • 相关阅读:
    KMP算法中next数组的构建
    vijos 1243 生产产品
    codeforces 557E Ann and Half-Palindrome
    codeforces 557D Vitaly and Cycle
    vijos 1054 牛场围栏 【想法题】
    oracle数据库基本操作
    一位90后程序员的自述:如何从年薪3w到30w
    Oracle 树操作(select…start with…connect by…prior)
    oracle中的条件语句
    重置按钮_reset
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3774078.html
Copyright © 2011-2022 走看看