leetcode_Evaluate Reverse Polish Notation
来源:互联网 发布:sqlserver 注释快捷键 编辑:程序博客网 时间:2024/06/13 00:52
描述:
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.就像题目所描述的,计算逆波兰数学表达式的结果,循环访问字符串数组类型的表达式
2.遍历的字符是数字,将数字进栈,是数学符号的时,将连续的两个数字出栈并计算出结果,然后将结果再入栈
3.重复步骤2直至所有的数组元素被访问完毕。
代码:
//代码通俗易懂,略冗余。
public int evalRPN(String[] tokens) { if(tokens==null||tokens.length==0) return 0; if(tokens.length==1) return Integer.parseInt(tokens[0]); int parseNum=0; int num1=0,num2=0; Stack<Integer>st=new Stack<Integer>(); for(int i=0;i<tokens.length;i++)//iterate the item of the array { if(isOperator(tokens[i]))//if the item is operator,caculate the numbers { num2=st.peek(); st.pop(); num1=st.peek(); st.pop(); parseNum=evaluteNums(num1,num2,tokens[i]); if(i+1==tokens.length) return parseNum; st.push(parseNum); }else {st.push(Integer.parseInt(tokens[i]));//if the item is number,push to the stack} } return parseNum; }public int evaluteNums(int num1,int num2,String operator){if(operator.equals("+"))return num1+num2;else if(operator.equals("-"))return num1-num2;else if(operator.equals("*"))return num1*num2;else return num1/num2;}public boolean isOperator(String str){char operator=str.charAt(0);if(operator=='+'||operator=='-'||operator=='*'||operator=='/'){if(str.length()==1)return true;}return false;}
0 0
- leetcode_Evaluate Reverse Polish Notation
- LeetCode_Evaluate Reverse Polish Notation
- leetcode_Evaluate Reverse Polish Notation
- leetcode_Evaluate Reverse Polish Notation
- leetcode_Evaluate Reverse Polish Notation
- leetcode_Evaluate Reverse Polish Notation
- LeetCode_evaluate-reverse-polish-notation
- Reverse Polish Notation
- calculate reverse polish notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Activity的启动模式
- iOS 设置导航栏的主题
- JAVA基础篇六(Java,C++中的流)
- Android onconfiguration属性
- 【费用流】 HDOJ 5352 MZL's City
- leetcode_Evaluate Reverse Polish Notation
- 解决NDK开发中Eclipse报错“Unresolved inclusion jni.h”的最终方法
- 欧拉通路-Play on Words
- 2015 大一集训心得
- 《乌合之众》思维导图及优秀读后感
- hdu 1695 GCD (欧拉函数、容斥原理)
- c++类实现基本的6种排序算法
- centos网络设置
- HTML5学习