150. Evaluate Reverse Polish Notation - LeetCode
发布时间:2020-12-14 21:52:25 所属栏目:大数据 来源:网络整理
导读:Question 150.?Evaluate Reverse Polish Notation Solution 2 1 + 3 * 是 ((2+1)*3) 的后缀(postfix)或逆波兰(reverse Polish)记法,计算这个表达式容易想到栈,当见到一个数时就入栈,见到操作符时该运算符作用于从该栈中弹出的两个数上,将所得结果入栈。
Question150.?Evaluate Reverse Polish Notation Solution
public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<>(); for (String tmp : tokens) { if (tmp.length() > 1) { stack.push(Integer.parseInt(tmp)); continue; } char c = tmp.charAt(0); // String转char int a,b; switch (c) { case '+': b = stack.pop(); a = stack.pop(); stack.push(a + b); break; case '-': b = stack.pop(); a = stack.pop(); stack.push(a - b); break; case '*': b = stack.pop(); a = stack.pop(); stack.push(a * b); break; case '/': b = stack.pop(); a = stack.pop(); stack.push(a / b); break; default: stack.push(c - '0'); // char 转 int } } return stack.pop(); } Reference
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |