Evaluate Reversed Polish Notation
来源:互联网 发布:梦里花落知多少百度云 编辑:程序博客网 时间:2024/04/29 19:28
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
wiki explanation for RPN:
http://en.wikipedia.org/wiki/Reverse_Polish_notation
Using Stack
public class Solution { public int evalRPN(String[] tokens) { //by stack //pay attention to minus and divide Stack<String> st = new Stack<String>(); int len = tokens.length; int res = 0; if(len == 0) return 0; if(len == 1) return Integer.parseInt(tokens[0]); for(int i=0; i<len; i++){ if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals ("*") || tokens[i].equals("/")){ int a = Integer.parseInt(st.pop()); int b = Integer.parseInt(st.pop()); if(tokens[i].equals ("+")){ st.push(String.valueOf(a+b)); } else if (tokens[i].equals ("-")){ st.push(String.valueOf(b-a)); // not a-b } else if(tokens[i].equals ("*")){ st.push(String.valueOf(a*b)); } else if(tokens[i].equals("/")){ st.push(String.valueOf(b/a)); // not a/b } } else { st.push(tokens[i]); } } res = Integer.parseInt(st.pop()); return res; }}
Eg: http://www.programcreek.com/2012/12/leetcode-evaluate-reverse-polish-notation/
0 0
- Evaluate Reversed 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
- 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
- Search Insert Position
- Reverse Linked List II -- LeetCode
- Single Number II
- Android开发Activity之间传递及获取数据
- ActionBar隐藏修改图标和标题
- Evaluate Reversed Polish Notation
- ActionBar自定义背景
- Populating Next Right Pointers in Each Node
- Remove Duplicates from Sorted List
- python--文件操作
- Climbing Stairs
- 如何使用java synchronized进行线程同步
- 从零单排c++ primer(17)
- Nginx 多站点配置