LeetCode OJ

这题是计算逆波兰表达式的最终值,使用stack的进栈出栈操作,可以很容易实现。

下面是AC代码:

 1 /**
 2      * Evaluate the value of an arithmetic expression in Reverse Polish Notation.
 3      * 这题就是进栈出栈
 4      * @param tokens
 5      * @return
 6      */
 7     public int evalRPN(String[] tokens){
 8          final int LENGTH = 100;
 9          int[] stack = new int[LENGTH];
10          int top = -1;
11          int temp = 0;
12          for(int i=0;i<tokens.length;i++)
13          { 
14              if(tokens[i].length() == 1)
15              {
16                  switch(tokens[i].charAt(0)) //陷阱:不能直接用tokens[i].charAt(0) 因为数字可以负数'-1',表示负数的符号和减号会冲突
17                  {
18                  case '+':
19                      temp = stack[top-1] + stack[top];
20                      stack[top-1] = temp;
21                      top--; break;
22                  case '-':
23                      temp = stack[top-1] - stack[top];
24                      stack[top-1] = temp;
25                      top--; break;
26                  case '*':
27                      temp = stack[top-1] * stack[top];
28                      stack[top-1] = temp;
29                      top--; break;
30                  case '/':
31                      temp = stack[top-1] / stack[top];
32                      stack[top-1] = temp;
33                      top--; break;
34                  default:
35                      stack[++top] = Integer.parseInt(tokens[i]);
36                  }
37              }
38              else
39                  stack[++top] = Integer.parseInt(tokens[i]);
40          } 
41          return stack[0]; 
42     }
有问题可以和我联系,bettyting2010#163 dot com
原文地址:https://www.cnblogs.com/echoht/p/3679895.html