leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation

Posted 银河末班车

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation相关的知识,希望对你有一定的参考价值。

leetcode 逆波兰式求解

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
import java.util.Stack;
public class Solution {
     public int evalRPN(String[] tokens) {
         Stack<Integer> stack = new Stack<Integer>();
        int tmp;
        for(int i = 0; i<tokens.length; i++){
            if("+".equals(tokens[i])){
                int a = stack.pop();
                int b = stack.pop();
                stack.add(b+a);
            }
            else if("-".equals(tokens[i])){
                int a = stack.pop();
                int b = stack.pop();
                stack.add(b-a);
            }
            else if("*".equals(tokens[i])){
                int a = stack.pop();
                int b = stack.pop();
                stack.add(b*a);
            }
            else if("/".equals(tokens[i])){
                int a = stack.pop();
                int b = stack.pop();
                stack.add(b/a);
            }
            else{
                stack.add(Integer.parseInt(tokens[i]));
            }
            
            
        }
        return stack.pop();
     }
}

根据你波兰式求值。看到逆波兰式可以想到栈,扫描表达式,遇到数字则将数字入栈,遇到运算符,时,则从栈顶弹出两个元素,后弹出的元素在运算符的左边,先弹出的元素在元素符的右边,执行运算,将结果入栈。扫描结束后,栈中的元素只剩下一个,即逆波兰式的值

以上是关于leetcode-Evaluate the value of an arithmetic expression in Reverse Polish Notation的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Evaluate Reverse Polish Notation (Python)

HDOJ 3974 Assign the task

asp.net mvc 中关于验证问题data-val-number="The field 部门号 must be a number

CodeForces 1084D The Fair Nut and the Best Path

My jquery isn't getting a value back with val() when the selector is working [closed]

POJ 3260 The Fewest Coins(多重背包+全然背包)