LeetCode--150. Evaluate Reverse Polish Notation
来源:互联网 发布:java多态的实现原理 编辑:程序博客网 时间:2024/06/05 18:29
题目:
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<Integer> num = new Stack<>();
int n=0;
for(int i = 0;i<tokens.length;i++){
if(tokens[i].equals("+")||tokens[i].equals("-")||tokens[i].equals("*")||tokens[i].equals("/")){//根据栈中的数据为操作符进行出栈,加减乘除操作
int num1 = num.pop();
int num2 = num.pop();
if(tokens[i].equals("+")){
n = num1+num2;
}
if(tokens[i].equals("-")){
n = num2-num1;
}
if(tokens[i].equals("*")){
n = num2*num1;
}
if(tokens[i].equals("/")){
n = num2/num1;
}
num.push(n);
}else{//栈中的数据为非操作符,则入栈
int m = Integer.parseInt(tokens[i]);//将数组中的数据转换为int
num.push(m);
}
}
return num.pop();
}
}
知识点:
数据类型转换,Integer.parseInt(String)就是将String字符类型数据转换为Integer整型数据,Integer.parseInt("20")=20;
Interger.valueOf("123")=Integer(123)这时候Integer(123)就是整数123的对象表示形式,它再调用intValue()方法,就是将123的对象表示形式转化为基本数据123
Integer.valueof()返回的是包装类Integer的对象
Integer.parseInt() 返回的是一个int的值
Integer.valueof().intValue();返回的也是一个int的值
- LeetCode 150. Evaluate Reverse Polish Notation
- [leetcode] 150.Evaluate Reverse Polish Notation
- 【leetcode】150. Evaluate Reverse Polish Notation
- Leetcode 150. Evaluate Reverse Polish Notation
- [LeetCode]150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation LeetCode
- Leetcode 150. Evaluate Reverse Polish Notation
- leetcode 150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- LeetCode *** 150. Evaluate Reverse Polish Notation
- leetcode-150. Evaluate Reverse Polish Notation
- LeetCode-150.Evaluate Reverse Polish Notation
- leetcode.150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- [leetcode] 150. Evaluate Reverse Polish Notation
- [leetcode] 【栈】150. Evaluate Reverse Polish Notation
- LeetCode - 150. Evaluate Reverse Polish Notation
- [LeetCode] 150. Evaluate Reverse Polish Notation
- HDU 5763
- Ultra-QuickSort
- Hive采集数据框架flume
- 网络编程(tcp、udp)
- FireFox插件RESTClient POST请求带json数据
- LeetCode--150. Evaluate Reverse Polish Notation
- Monte Carlo方法
- Super Jumping! Jumping! Jumping!||HDU1087
- 难度较大的网络线程
- 使用intellij idea开发cordova项目
- 重写重载20170806
- Excel
- 仿天猫购物商城项目
- redis常用操作数据命令及场景