LeetCode(150)-Evaluate Reverse Polish Notation 計算逆波蘭表達式

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.Scanner;
import java.util.Stack;

public class l150_reverse_polish_notation {
    public int evalRPN(String[] tokens) {
        Stack<Integer> s=new Stack<>();
        for(int i=0;i<tokens.length;i++){
            if(tokens[i].equals("+")||tokens[i].equals("-")||tokens[i].equals("*")||tokens[i].equals("/")){
                int num2=s.pop();
                int num1=s.pop();
                s.push(operate(tokens[i],num1,num2));

            }
            else{
                s.push(Integer.valueOf(tokens[i]));

            }
        }
        return s.pop();
        }
        public  int operate(String op,int num1,int num2){

            if(op.equals("+"))
               return  num1+num2;
            if(op.equals("-"))
               return  num1-num2;
            if(op.equals("*"))
                return num1*num2;
            if(op.equals("/"))
               return  num1/num2;
            return 0;
        }
    public static void main(String[] args) {
        l150_reverse_polish_notation c=new l150_reverse_polish_notation();
        Scanner scanner=new Scanner(System.in);
        String[] tokens=new String[5];
        for(int i=0;i<tokens.length;i++){
            tokens[i]=scanner.next();
        }
        int res=c.evalRPN(tokens);
        System.out.println(res);
    }
}

貼一下牛客上的答案,異常處理應用:

鏈接:https://www.nowcoder.com/questionTerminal/22f9d7dd89374b6c8289e44237c70447
來源:牛客網

import java.util.Stack;
public class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        for(int i = 0;i<tokens.length;i++){
            try{
                int num = Integer.parseInt(tokens[i]);
                stack.add(num);
            }catch (Exception e) {
                int b = stack.pop();
                int a = stack.pop();
                stack.add(get(a, b, tokens[i]));
            }
        }
        return stack.pop();
    }
    private int get(int a,int b,String operator){
        switch (operator) {
        case "+":
            return a+b;
        case "-":
            return a-b;
        case "*":
            return a*b;
        case "/":
            return a/b;
        default:
            return 0;
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章