Leetcode Evaluate Reverse Polish Notation

OpenSoucre發表於2014-06-18

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();
}

 

 

相關文章