码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Evaluate Reverse Polish Notation

时间:2014-06-28 22:31:11      阅读:323      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   数据      

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即可,此题的改进版本是引入括号,此时要开一个数据stack和运算符stack
bool isOperator(string& op){
    if(op == "+" ||  op == "-" || op == "*" || op == "/") return true;
    else return false;
}

int calc(int a, int b, char op){
    switch(op){
        case +:return a+b;
        case -:return a-b;
        case *:return a*b;
        case /:return a/b;
    }
}

int evalRPN(vector<string> &tokens){
    stack<int> num;
    for(int i = 0 ; i < tokens.size(); ++ i){
        if(!isOperator(tokens[i])){
            num.push(atoi(tokens[i].c_str()));
        }else{
            int num2 = num.top(); num.pop();
            int num1 = num.top(); num.pop();
            char op = tokens[i][0];
            num.push(calc(num1,num2,op));
        }
    }
    return num.top();
}

 

 

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

Leetcode Evaluate Reverse Polish Notation

标签:style   blog   http   color   数据      

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3794372.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!