Convert Expression to Reverse Polish Notation

时间:2021-04-14 19:35:12

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", "+"])

 public class Solution {
public List<String> convertToRPN(String[] expression) {
List<String> list = new ArrayList<>();
Stack<String> stack = new Stack<>(); for (String str : expression) {
if (isOperator(str)) {
if (str.equals("(")) {
stack.push(str);
} else if (str.equals(")")) {
while (!stack.isEmpty() && !stack.peek().equals("(")) {
list.add(stack.pop());
}
stack.pop();
} else {
while (!stack.isEmpty() && order(str) <= order(stack.peek())) {
list.add(stack.pop());
}
stack.push(str);
}
} else {
list.add(str);
}
}
while (!stack.isEmpty()) {
list.add(stack.pop());
}
return list;
} private boolean isOperator(String str) {
if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/") || str.equals("(")
|| str.equals(")")) {
return true;
}
return false;
} private int order(String a) {
if (a.equals("*") || a.equals("/")) {
return ;
} else if (a.equals("+") || a.equals("-")) {
return ;
} else {
return ;
}
}
}

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