首页 > 其他 > 详细

Leetcode 150. Evaluate Reverse Polish Notation

时间:2016-07-16 20:17:33      阅读:251      评论:0      收藏:0      [点我收藏+]

不定期更新leetcode解题java答案。

采用pick one的方式选择题目。 

题意为给定类似树结构运算符后缀的计算序列,返回计算结果。

 ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

可看出后进数字先计算,采用栈来储存数字,出现运算符则出栈运算,并将运算后的结果再次放入栈中,最后的运算结束时,栈中存留一个值为计算结果。

代码如下:

 1 public class Solution {
 2     public int evalRPN(String[] tokens) {
 3         Stack<Integer> stack = new Stack();
 4         for(int i = 0; i < tokens.length; i++){
 5             if(tokens[i].charAt(tokens[i].length() - 1) >= ‘0‘ && tokens[i].charAt(tokens[i].length() - 1) <= ‘9‘)
 6                 stack.push(Integer.parseInt(tokens[i]));
 7             else{
 8                 int num2 = stack.pop();
 9                 int num1 = stack.pop();
10                 stack.push(calculate(num1, num2, tokens[i]));
11             }
12         }
13         return stack.pop();
14     }
15     
16     public int calculate(int num1, int num2, String str){
17         if(str.equals("+"))
18             return num1 + num2;
19         else if(str.equals("-"))
20             return num1 - num2;
21         else if(str.equals("*"))
22             return num1 * num2;
23         else 
24             return num1 / num2;
25     }
26 }

 

Leetcode 150. Evaluate Reverse Polish Notation

原文:http://www.cnblogs.com/zslhq/p/5676966.html

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