Convert Expression to Reverse Polish Notation

Given an expression string array, return the Reverse Polish notation of this expression. (remove the parentheses)

Example

For the expression [3 - 4 + 5] (which denote by ["3", "-", "4", "+", "5"]), return [3 4 - 5 +] (which denote by ["3", "4", "-", "5", "+"])

 1 public class Solution {
 2     public List<String> convertToRPN(String[] expression) {
 3         List<String> list = new ArrayList<>();
 4         Stack<String> stack = new Stack<>();
 5 
 6         for (String str : expression) {
 7             if (isOperator(str)) {
 8                 if (str.equals("(")) {
 9                     stack.push(str);
10                 } else if (str.equals(")")) {
11                     while (!stack.isEmpty() && !stack.peek().equals("(")) {
12                         list.add(stack.pop());
13                     }
14                     stack.pop();
15                 } else {
16                     while (!stack.isEmpty() && order(str) <= order(stack.peek())) {
17                         list.add(stack.pop());
18                     }
19                     stack.push(str);
20                 }
21             } else {
22                 list.add(str);
23             }
24         }
25         while (!stack.isEmpty()) {
26             list.add(stack.pop());
27         }
28         return list;
29     }
30 
31     private boolean isOperator(String str) {
32         if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/") || str.equals("(")
33                 || str.equals(")")) {
34             return true;
35         }
36         return false;
37     }
38 
39     private int order(String a) {
40         if (a.equals("*") || a.equals("/")) {
41             return 2;
42         } else if (a.equals("+") || a.equals("-")) {
43             return 1;
44         } else {
45             return 0;
46         }
47     }
48 }

相关问题:Evaluate Reverse Polish Notation ( https://www.cnblogs.com/beiyeqingteng/p/5679265.html )

转载于:https://www.cnblogs.com/beiyeqingteng/p/5691242.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值