`

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;
} 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics