Leetcode-evaluate-reverse-polish-notation
2016-07-16 20:16
405 查看
题目描述
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
给你逆波兰表达式,计算结果。
思路:遇到数字进栈,遇到运算符,弹出栈中最上面的两个数,计算的结果入栈。
import java.util.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<String>();
for(int i=0; i<tokens.length; i++){
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")){
String two = stack.pop();
String one = stack.pop();
int a = Integer.parseInt(one);
int b = Integer.parseInt(two);
int res = 0;
if(tokens[i].equals("+")){
res = a + b;
}
if(tokens[i].equals("-")){
res = a - b;
}
if(tokens[i].equals("*")){
res = a * b;
}
if(tokens[i].equals("/")){
res = a / b;
}
stack.push(String.valueOf(res));
}else{
stack.push(tokens[i]);
}
}
return Integer.parseInt(stack.pop());
}
}
相关文章推荐
- Lua教程(四):在Lua中调用C语言、C++的函数
- Lua教程(二):C++和Lua相互传递数据示例
- Lua教程(三):C语言、C++中调用Lua的Table示例
- Lua教程(五):C/C++操作Lua数组和字符串示例
- 和我一起写lua - C和lua的参数传递与返回值
- lua-string-resty的aes加密解密,无法和python的aes进行对接
- ulua经验
- ulua使用经验
- Lua类继承的优雅实现方式
- ulua热更新小demo
- C++11 lambda表达式 实际上是lua的闭包方式
- Lua基础[持续更新]
- ubuntu 下安装lua语言
- 【记录】Lua中冒号的意义
- Lua 在移动平台上的应用
- python中嵌入lua解析器
- 详解Lua中的元表概念
- Lua math中各个方法对照表
- lua类的写法
- lua快速入门