`

LintCode - Infix to Postfix / Convert Expression to Reverse Polish Notation

 
阅读更多

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

Aka, convert infix notation to postfix notation.

 

Example

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

public List<String> convertToRPN(String[] expression) {
    List<String> rpn = new ArrayList<>();
    Stack<String> opstack = new Stack<>();
    for(String op:expression) {
        if("+-*/".contains(op)) {
            while(!opstack.isEmpty() && getPriority(opstack.peek()) >= getPriority(op)) {
                rpn.add(opstack.pop());
            }
            opstack.push(op);
        } else if("(".equals(op)) {
            opstack.push(op);
        } else if(")".equals(op)) {
            while(!"(".equals(opstack.peek())) {
                rpn.add(opstack.pop());
            }
            opstack.pop();
        }
        else {
            rpn.add(op);
        }
    }
    while(!opstack.isEmpty()) {
        rpn.add(opstack.pop());
    }
    return rpn;
}
private int getPriority(String s) {
    char c = s.charAt(0);
    if(c == '+' || c== '-') {
        return 1;
    } else if(c == '*' || c == '/') {
        return 2;
    }
    return 0;
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics