首页 > 编程语言 > 详细

[Leetcode][JAVA] Evaluate Reverse Polish Notation

时间:2014-09-10 05:07:10      阅读:297      评论:0      收藏:0      [点我收藏+]

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


使用栈即可实现。遇到运算符号即pop出俩数运算,否则push
由于测试用例没有非法的表达式,所以很容易即可ACCEPT

 1 public int evalRPN(String[] tokens) {
 2         Stack<String> st = new Stack<String>();
 3         for(int i=0;i<tokens.length;i++)
 4         {
 5             String t = tokens[i];
 6             if(t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/"))
 7             {
 8                 int x2 = Integer.parseInt(st.pop());
 9                 int x1 = Integer.parseInt(st.pop());
10                 if (t.equals("+"))
11                     st.push(String.valueOf(x1 + x2));
12                 else if (t.equals("-"))
13                     st.push(String.valueOf(x1 - x2));
14                 else if (t.equals("*"))
15                     st.push(String.valueOf(x1 * x2));
16                 else
17                     st.push(String.valueOf(x1 / x2));
18             }
19             else
20                  st.push(t);
21         }
22         
23         return Integer.parseInt(st.pop());
24     }

 



[Leetcode][JAVA] Evaluate Reverse Polish Notation

原文:http://www.cnblogs.com/splash/p/3963665.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!