本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

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

分析:这一题就是写程序计算逆波兰式的结果,遍历表达式,碰到操作数入栈,碰到操作符就从栈顶取出两个操作数,再将计算后的结果入栈,最后栈中剩余的唯一操作数就是计算结果。                                                        本文地址

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string> &tokens) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         int len = tokens.size();
 7         stack<int> S;
 8         for(int i = 0; i < len; i++)
 9         {
10             if(tokens[i] == "+" || tokens[i] == "-" ||
11                 tokens[i] == "*" || tokens[i] == "/")
12             {
13                 int op2 = S.top(); S.pop();
14                 int op1 = S.top(); S.pop();
15                 S.push( op(op1, op2, tokens[i][0]) );
16             }
17             else
18                 S.push(stoi(tokens[i]));
19         }
20         return S.top();
21     }
22     int op(int op1, int op2, char optor)
23     {
24         if(optor == '+')return op1 + op2;
25         else if(optor == '-')return op1 - op2;
26         else if(optor == '*')return op1 * op2;
27         else return op1 / op2;
28     }
29 };

【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3448626.html

posted @ 2013-11-28 22:42  tenos  阅读(3241)  评论(0编辑  收藏  举报

本博客rss订阅地址: http://feed.cnblogs.com/blog/u/147990/rss

公益页面-寻找遗失儿童