力扣150题(逆波兰表达式求值)
150、逆波兰表达式求值
基本思想:
和1047题想法是差不多,只不过本题不要相邻元素做消除了,而是做运算
具体实现:
代码:
class Solution { public int evalRPN(String[] tokens) { Deque<Integer> stack = new LinkedList(); for (String token : tokens) { char c = token.charAt(0); if (!isOpe(token)) {//不是运算符,注意“-11”这种情况
//每个运算对象可以是整数,也可以是另一个逆波兰表达式。["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
stack.addFirst(stoi(token)); } else if (c == '+'){ stack.push(stack.pop() + stack.pop()); } else if (c == '*'){ stack.push(stack.pop() * stack.pop()); } else if (c == '-'){ stack.push(-stack.pop() + stack.pop()); } else { int num1 = stack.pop(); int num2 = stack.pop(); stack.push(num2/num1); } } return stack.pop(); } private boolean isOpe(String s){//判断是否是运算符 return s.length() == 1 && s.charAt(0) < '0' || s.charAt(0) > '9'; } private int stoi(String s){ return Integer.valueOf(s); } }
class Solution { public int evalRPN(String[] tokens) { Deque<Integer> stack = new LinkedList(); for (int i = 0; i < tokens.length; ++i) { if ("+".equals(tokens[i])) { // leetcode 内置jdk的问题,不能使用==判断字符串是否相等 stack.push(stack.pop() + stack.pop()); // 注意 - 和/ 需要特殊处理 } else if ("-".equals(tokens[i])) { stack.push(-stack.pop() + stack.pop()); } else if ("*".equals(tokens[i])) { stack.push(stack.pop() * stack.pop()); } else if ("/".equals(tokens[i])) { int temp1 = stack.pop(); int temp2 = stack.pop(); stack.push(temp2 / temp1); } else { stack.push(Integer.valueOf(tokens[i])); } } return stack.pop(); } }