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

Leetcode: Evaluate Reverse Polish Notation

时间:2014-12-15 23:15:31      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

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  

分析:Reverse Polish Notation可以通过post traversal计算树来得到,我们可以通过栈来evaluate它的值,代码如下:
 1 class Solution {
 2 public:
 3     int evalRPN(vector<string> &tokens) {
 4         int result = 0;
 5         stack<int> S;
 6         
 7         for(int i = 0; i < tokens.size(); i++){
 8             if(is_operator(tokens[i])){
 9                 int rv = S.top();
10                 S.pop();
11                 int lv = S.top();
12                 S.pop();
13                 if(tokens[i] == "+")
14                     S.push(lv + rv);
15                 else if(tokens[i] == "-")
16                     S.push(lv - rv);
17                 else if(tokens[i] == "*")
18                     S.push(lv * rv);
19                 else if(tokens[i] == "/")
20                     S.push(lv / rv);
21             }else{
22                 S.push(atoi(tokens[i].c_str()));
23             }
24         }
25         return S.top();
26     }
27     
28     bool is_operator(string s){
29         return s == "+" || s == "-" || s == "*" || s == "/";
30     }
31 };

 

Leetcode: Evaluate Reverse Polish Notation

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/Kai-Xing/p/4165923.html

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