【Leetcode】Evaluate Reverse Polish Notation答案
来源:互联网 发布:SQL索引超出了数组界限 编辑:程序博客网 时间:2024/06/16 14:39
一、原题
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
二、分析
这里的分析就援引百度文库对于逆波兰表达式的计算方法。
“它的优势在于只用两种简单操作,入栈和出栈就可以搞定任何普通表达式的运算。其运算方式如下:
如果当前字符为变量或者为数字,则压栈,如果是运算符,则将栈顶两个元素弹出作相应运算,结果再入栈,最后当表达式扫描完后,栈里的就是结果。”
三、代码(JAVA)
import java.util.Stack;public class ReversePolishNotation {Stack<String> stack =new Stack();public int evalRPN(String[] tokens) {if(tokens.length==0)return 0;int temp1,temp2,temp3;temp1=temp2=temp3=0; for(int i=0;i<tokens.length;i++){ if(tokens[i].equals("+")|| tokens[i].equals("-")|| tokens[i].equals("*")|| tokens[i].equals("/")){ if(tokens.length==1) return 0; temp1=Integer.parseInt(stack.peek()); stack.pop(); temp2=Integer.parseInt(stack.peek()); stack.pop(); if(tokens[i].equals("+")){ temp3=temp1+temp2; stack.push(Integer.toString(temp3));//计算结果同样要入栈 } else if(tokens[i].equals("*")){ temp3=temp1*temp2; stack.push(Integer.toString(temp3)); } else if(tokens[i].equals("/")){ temp3=temp2/temp1; // 注意temp2与temp1的顺序 stack.push(Integer.toString(temp3)); } else if(tokens[i].equals("-")){ temp3=temp2-temp1; stack.push(Integer.toString(temp3)); } } else{ temp3=Integer.parseInt(tokens[i]);//这里针对输入类似{“18”},既(s.length==1)&&(s[0]代表数字) stack.push(tokens[i]); } }return temp3; }}
0 0
- leetcode题目--Evaluate Reverse Polish Notation 答案
- 【Leetcode】Evaluate Reverse Polish Notation答案
- Evaluate Reverse Polish Notation | leetcode
- 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
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode-Evaluate Reverse Polish Notation
- LeetCode:Evaluate Reverse Polish Notation
- android 控制POS机图文打印(二)
- 在应用层通过spring特性解决数据库读写分离
- navicat 快捷键
- Android 在Activity之间传递数据
- C#+AE调用ArcToolbox工具
- 【Leetcode】Evaluate Reverse Polish Notation答案
- linux的apk重签名脚本
- 第三方系统通过IFrame的方式访问BIEE报表
- js获取浏览器滚动条距离顶端的距离
- 设置Android自定义标题栏的背景色和字体的大小
- lucene4.10学习笔记1
- shell中sed的使用
- hdu1023 Train Problem II(卡特兰数)
- web测试—总结不错的web测试文章