首页 > 代码库 > Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation
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
这道题还是比较Easy,直接用堆栈,遇到数字就进栈,遇到运算符弹出两个数,将运算结果入栈。最后返回栈底元素就okay了
public class Solution { public int evalRPN(String[] tokens) { int top = -1;//栈指针 int stack[] = new int[tokens.length / 2 + 1]; for(int i = 0; i < tokens.length; i++){ char temp = tokens[i].charAt(0); if(temp != ‘+‘ && !(tokens[i].length() == 1 && temp == ‘-‘) && temp != ‘*‘ && temp != ‘/‘){//数字直接入栈 stack[++top] = Integer.valueOf(tokens[i]); } else{//元素符,弹两个数字出来计算 int num1; int num2; int result = 0; num2 = stack[top--]; num1 = stack[top--]; switch(temp){ case ‘+‘: result = num1 + num2; break;//入栈 case ‘-‘: result = num1 - num2; break; case ‘*‘: result = num1 * num2; break; case ‘/‘: result = num1 / num2; break; } stack[++top] = result;//结果入栈 } } return stack[top]; }}
Evaluate Reverse Polish Notation
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。