首页 > 代码库 > Leetcode 448. 150. Evaluate Reverse Polish Notation JAVA语言
Leetcode 448. 150. Evaluate Reverse Polish Notation JAVA语言
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 Subscribe to see which companies asked this question.
题意:求逆波兰表达式的结果
public class Solution { public int isopnd(String s){ if(s.length()!=1)return 0; char c=s.charAt(0); switch(c){ case ‘+‘: return 1; case ‘-‘: return 2; case ‘*‘: return 3; case ‘/‘: return 4; default:return 0; } } public int evalRPN(String[] tokens) { if(tokens.length==1) return Integer.valueOf(tokens[0]); Stack<Integer> stack=new Stack<Integer>(); int ans=0; for(String tk : tokens){ int op=isopnd(tk); if(op!=0){ int a=stack.peek(); stack.pop(); int b=stack.peek(); stack.pop(); if(op==1){ ans=a+b; } if(op==2){ ans=b-a; } if(op==3){ ans=a*b; } if(op==4){ ans=b/a; } System.out.println(ans); stack.push(ans); }else{ stack.push(Integer.valueOf(tk)); } } return ans; } }
PS:用栈。第一次调用栈。遇到数字,入栈,遇到运算符,出栈俩数字做计算,结果再入栈。
Leetcode 448. 150. Evaluate Reverse Polish Notation JAVA语言
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。