本文共 1132 字,大约阅读时间需要 3 分钟。
Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in .
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6Java代码:
public class Solution { public int evalRPN(String[] tokens) { Stackstack = new Stack<>(); if (tokens.length == 0) return 0; for (int i = 0; i < tokens.length; i++) { if (isNum(tokens[i])) { stack.push(Integer.parseInt(tokens[i])); } else { Integer n2 = stack.pop(); Integer n1 = stack.pop(); Integer result; if (tokens[i].equals("+")) { result = n1 + n2; stack.push(result); } else if (tokens[i].equals("-")) { result = n1 - n2; stack.push(result); } else if (tokens[i].equals("*")) { result = n1 * n2; stack.push(result); } else if (tokens[i].equals("/")) { result = n1 / n2; stack.push(result); } } } return stack.pop(); } public boolean isNum(String s) { try { Integer.parseInt(s); return true; } catch (Exception e) { return false; } }}
转载地址:http://zpuni.baihongyu.com/