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即可,此题的改进版本是引入括号,此时要开一个数据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();
}

 

 
posted @ 2014-06-18 12:32  OpenSoucre  阅读(137)  评论(0编辑  收藏  举报