🌻算法,不如说它是一种思考方式🍀
算法专栏: 👉🏻123
"+"、"-"、"*" 或 "/"
),或是在范围 [-200, 200] 内的一个整数'+'、'-'、'*' 和 '/'
。逆波兰表达式:
逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。
平常使用的算式则是一种中缀表达式,如( 1 + 2 ) * ( 3 + 4 )
。
该算式的逆波兰表达式写法为( ( 1 2 + ) ( 3 4 + ) * )
。
逆波兰表达式主要有以下两个优点:
去掉括号后表达式无歧义,上式即便写成1 2 + 3 4 + *
也可以依据次序计算出正确结果。
适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中。
遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中:
class Solution {public int evalRPN(String[] tokens) {Stack<String> stack=new Stack<>();int ans=0;for (String token:tokens) {switch (token){case "+":ans= Integer.parseInt(stack.pop())+Integer.parseInt(stack.pop());stack.push(String.valueOf(ans));break;case "-":ans= Integer.parseInt(stack.pop());ans=Integer.parseInt(stack.pop())-ans;stack.push(String.valueOf(ans));break;case "*":ans= Integer.parseInt(stack.pop())*Integer.parseInt(stack.pop());stack.push(String.valueOf(ans));break;case "/":ans= Integer.parseInt(stack.pop());ans=Integer.parseInt(stack.pop())/ans;stack.push(String.valueOf(ans));break;default:stack.push(token);}}int str=Integer.parseInt(stack.pop());return str;}
}
返回第一页。☝
☕物有本末,事有终始,知所先后。🍭
🍎☝☝☝☝☝我的CSDN☝☝☝☝☝☝🍓
本文发布于:2024-01-31 19:40:26,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170670122630898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |