发布网友 发布时间:2022-04-14 20:52
共3个回答
懂视网 时间:2022-04-15 01:14
Evaluate the value of arithmetic expression in Reverse Polish Notation. Valid operator are ,-,*,/. Each operand may be an integer or another expression. Some examples: [2, 1, , 3, *] - ((21)*3) - 9 [4, 13, 5, /, ] - (4 (13 / 5)) - 6 分析:
Evaluate the value of arithmetic expression in Reverse Polish Notation.
Valid operator 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) { Stackst = new Stack (); for(String token : tokens){ if(token.matches("-?[0-9]+")){ st.push(Integer.parseInt(token)); }else{ int num2 = st.pop(); int num1 = st.pop(); if(token.equals("+")){ st.push(num1+num2); }else if(token.equals("-")){ st.push(num1-num2); }else if(token.equals("*")){ st.push(num1*num2); }else if(token.equals("/")){ st.push(num1/num2); } } } return st.pop(); } }
热心网友 时间:2022-04-14 22:22
你可以选择用C++去写啊,题目本身跟语言无关热心网友 时间:2022-04-14 23:40
每道题都可以选择你的答题语言。leetcode支持多种语言的。