Convert Expression to Reverse Polish Notation

public class Solution {
    
    private static Map<String, Integer> priorityMap = new HashMap<>();
    
    static {
        priorityMap.put("*", 3);
        priorityMap.put("/", 3);
        priorityMap.put("+", 2);
        priorityMap.put("-", 2);
    }
    
    /**
     * @param expression: A string array
     * @return: The Reverse Polish notation of this expression
     */
    public List<String> convertToRPN(String[] expression) {
        // write your code here
        if (expression == null) {
            return null;
        }
        
        List<String> result = new ArrayList<>();
        Stack<String> stack = new Stack<>();
        
        for (String exp : expression) {
            if (Character.isDigit(exp.charAt(0))) {
                result.add(exp);
            } else if ("(".equals(exp)) {
                stack.push("(");
            } else if (")".equals(exp)) {
                while (!"(".equals(stack.peek())) {
                    result.add(stack.pop());
                }
                stack.pop();
            } else {
                int priority = priorityMap.getOrDefault(exp, 1);
                while (!stack.isEmpty() && priority <= priorityMap.getOrDefault(stack.peek(), 1)) {
                    result.add(stack.pop());
                }
                stack.push(exp);
            }
        }
        
        while (!stack.isEmpty()) {
            result.add(stack.pop());
        }
        
        return result;
    }
}

最后更新于

这有帮助吗?