/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
class Solution { public int evalRPN(String[] tokens) { //定义保存符号的Stack Stack<String> stack = new Stack<>(); Map<String, Integer> dict = new HashMap<>(); dict.put("+", 1); dict.put("-", 2); dict.put("*", 3); dict.put("/", 4);
for(String str : tokens){ if(dict.containsKey(str)){ int second = Integer.parseInt(stack.pop()); int first = Integer.parseInt(stack.pop()); int result = 0; if(dict.get(str) == 1){ result = first + second; }elseif(dict.get(str) == 2){ result = first - second; }elseif(dict.get(str) == 3){ result = first * second; }else{ result = first / second; } stack.push(String.valueOf(result)); }else{ stack.push(str); } } return Integer.parseInt(stack.pop()); } }
//优化之后的代码 class Solution { public int evalRPN(String[] tokens) { Deque<Integer> stack = newLinkedList(); for (String s : tokens) { if ("+".equals(s)) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等 stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理 } elseif ("-".equals(s)) { stack.push(-stack.pop() + stack.pop()); } elseif ("*".equals(s)) { stack.push(stack.pop() * stack.pop()); } elseif ("/".equals(s)) { int temp1 = stack.pop(); int temp2 = stack.pop(); stack.push(temp2 / temp1); } else { stack.push(Integer.valueOf(s)); } } return stack.pop(); } }