【leetcode刷题笔记】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

题解:典型的栈的应用——计算后缀表达式。

思路很简单:

遇到符号就从栈里面弹出来两个元素进行相应的计算后得到的结果重新放回栈中

遇到数字就直接压入栈中。

代码如下:

 1 public class Solution {
 2    public int evalRPN(String[] tokens) {
 3         Stack<Integer> s = new Stack<Integer>();
 4 
 5         for(String x:tokens){
 6             if(x.equals("+"))
 7                 s.push(s.pop()+s.pop());
 8             else if(x.equals("-")){
 9                 int b = s.pop();
10                 int a = s.pop();
11                 s.push(a-b);
12             }
13             else if(x.equals("*"))
14                 s.push(s.pop()*s.pop());
15             else if(x.equals("/")){
16                 int b = s.pop();
17                 int a = s.pop();
18                 s.push(a/b);
19             }
20             else{
21                 s.push(Integer.parseInt(x));
22             }
23         }
24         
25         return s.pop();
26         
27     }
28 }

特别注意的地方有两点:

1.将一个String转换成Integer用Integer.parseInt()函数

2.开始我用的是“==”来比较两个字符串是否相等,后来发现“==”其实比较的是字符串的地址是否相等,如果要比较字符串的内容是否相等要用s.equals()函数。

  不过很奇怪的一点是在自己电脑的eclipse上面用“==”居然也能够算出正确的值。

原文地址:https://www.cnblogs.com/sunshineatnoon/p/3836530.html