首页 > 代码库 > LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation

LeetCode: Reverse Words in a String:Evaluate Reverse Polish Notation

LeetCode: Reverse Words in a String: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

地址:https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
计算波兰后缀表达式的值,具体做法是利用一个栈,如果遇到数字则把数字进栈,如果遇到操作符就把栈中的数字出栈进行运算(二元操作符出栈两个数字,一元操作符出栈一个数字),最后的结果存在栈中。代码:
 1 class Solution { 2 public: 3     int evalRPN(vector<string> &tokens) { 4         int lop, rop; 5         vector<string>::const_iterator cIter = tokens.begin(); 6         stack<int> s; 7         for(; cIter != tokens.end(); ++cIter){ 8             if ((*cIter).size() == 1 && !isdigit((*cIter)[0])){ 9                 char op = (*cIter)[0];10                 rop = s.top();11                 s.pop();12                 lop = s.top();13                 s.pop();14                 if (+ == op){15                     s.push(lop + rop);16                 } else if (- == op){17                     s.push(lop - rop);18                 } else if (* == op){19                     s.push(lop * rop);20                 } else{21                     s.push(lop / rop);22                 }23             } else {24                 s.push(atoi((*cIter).c_str()));25             }26         }27         return s.top();28     }29 };