LintCode - Infix to Prefix / Convert Expression to Polish Notation

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

Aka, convert infix notation to prefix notation. 

Example

For the expression [(5 − 6) * 7] (which represented by["(", "5", "−", "6", ")", "*", "7"]), the corresponding polish notation is [* - 5 6 7] (which the return value should be["*", "−", "5", "6", "7"]).

public List<String> convertToPN(String[] expression) {
    Stack<String> operand = new Stack<>();
    Stack<String> operator = new Stack<>();
    for(int i=expression.length-1; i>=0; i--) {
        String s = expression[i];
        if("+-*/".contains(s)) {
            // note: must be >, not >=
            while(!operator.isEmpty() && getPriority(operator.peek()) > getPriority(s)) {
                operand.push(operator.pop());
            }
            operator.push(s);
        } else if(")".equals(s)) {
            operator.push(s);
        } else if("(".equals(s)) {
            while(!operator.peek().equals(")")) {
                operand.push(operator.pop());
            }
            operator.pop();
        } else {
            operand.push(s);
        }
    }
    while(!operator.isEmpty()) {
        operand.push(operator.pop());
    }
    List<String> pn = new ArrayList<>(operand);
    Collections.reverse(pn);
    return pn;
}

private int getPriority(String s) {
    char c = s.charAt(0);
    if(c=='+' || c=='-') return 1;
    if(c=='*' || c=='/') return 2;
    return 0;
} 
 

猜你喜欢

转载自yuanhsh.iteye.com/blog/2215781
今日推荐