首页 > 代码库 > LeetCode 2 Evaluate Reverse Polish Notation
LeetCode 2 Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
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)) -> 6
解析,利用栈结构,正确解析后缀表达式的顺序,应该是从左到直右扫描之后,在进行计算时,计算的次序于原来后缀表达式的次序相同,否则会发现除以零的错误!
public class Solution { public int evalRPN(String[] tokens) { Deque<Integer> stack = new ArrayDeque<Integer>(); for (int i = 0; i < tokens.length; i++) { if ((tokens[i].charAt(0) >= '0' && tokens[i].charAt(0) <= '9') || (tokens[i].charAt(0) == '-' && tokens[i].length() > 1)) { stack.push(Integer.parseInt(tokens[i])); } else { int x = stack.pop(); int y = stack.pop(); switch (tokens[i].charAt(0)) { case '+': stack.push(y + x); break; case '-': stack.push(y - x); break; case '*': stack.push(y * x); break; case '/': stack.push(y / x); break; default: break; } } } return stack.pop(); } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。