您好,欢迎来到芙姬情感网。
搜索
您的当前位置:首页LeetCode2EvaluateReversePolishNotation

LeetCode2EvaluateReversePolishNotation

来源:芙姬情感网


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) {
 Stack st = 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();
 }
}

Copyright © 2019- fujy.cn 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务