Problem link:

http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/


According to the wiki page, the algorithm for evaluating any postfix expression is fairly straightforward. The following is the pseudo-code for evaluating a postfix expression.

while there are input tokens left
read the next token from input
if the token is a value (operand)
push it into the stack
else (the token is an operator)
let n be the number of the arguments of the operator
if there are fewer than n values in the stack
return ERROR (non-sufficient operands in the expression)
else
pop the top n values from the stack
evaluate the expression with the operator and operands
push the result, if any, back into the stack
if there is only one value in the stack
return the value as the result
else
return ERROR (too many operands in the expression)

However, in this problem, it is much easier since there are only four operators. What we need to concern is only to identify the operators and numbers (integer in this case). Therefore, we will implement two functions:

  • A stack structure
  • Functions on a string that determine the string is an integer or an operator.

The C++ implementation of the algorithm is as follows.

#include <stack>
#include <ctype.h> class Solution {
public:
int evalRPN(vector<string> &tokens) {
// The stack to store operators (int values) only
std::stack<int> res;
int x,y;
// Iterate the vector from left to right
for(std::vector<string>::iterator it = tokens.begin(); it != tokens.end(); it++)
{
// If operator, pop and evaluate
if ( (*it).length() == 1 && !isdigit((*it)[0]) ) {
y = res.top();
res.pop();
x = res.top();
res.pop();
if (*it == "+") x += y;
else if (*it == "-") x -= y;
else if (*it == "*") x *= y;
else if (*it == "/") x /= y;
res.push(x);
}
// If operand, push it into the stack
else res.push( atoi((*it).c_str()) );
}
// The only value left in the stack is the final result
return res.top();
}
};

最新文章

  1. STL学习
  2. 线性代数 -- Linear Algebra with Applications
  3. linux hugepage
  4. Http之Get/Post请求区别
  5. IPy的使用
  6. 【HTML】Intermediate1:Span&amp;Div
  7. 第一次尝试使用JAVA编写的ATM机程序
  8. css3 页面退出和进入的动画
  9. socket.io 入门篇(二)
  10. openstack集群环境准备
  11. luogu4166 最大土地面积 (旋转卡壳)
  12. 『高性能模型』卷积复杂度以及Inception系列
  13. UVA1103-Ancient Messages(脑洞+dfs)
  14. left join 右表数据不唯一的情况解决方法
  15. golang匿名结构体
  16. usbserials
  17. 【PyQt5-Qt Designer】按钮系列
  18. chkconfig 管理系统服务
  19. linux系统编程之信号(五):信号集操作函数,信号阻塞与未决
  20. openwrt&lt;转载--openwrt框架分析 &gt;

热门文章

  1. PHP Warning: ob_start() : output handler &#39;ob_gzhandler conflicts with &#39;zlib output compression&#39;
  2. inline-block的简单理解
  3. 模拟器的tableView的分割线不显示
  4. 集成 Apple Pay
  5. ooize简介
  6. Python环境的安装
  7. Objective-C:@class和#import
  8. Windows Store App 应用程序安装目录
  9. spring mvc读取url变量
  10. 使用Linq快速的操作XML