leetcode--栈

题目1:用栈实现 数字的各种可能计算 (根据顺序)

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> ();
        for(int  i=0;i<tokens.length;i++){
            try{
                int num=Integer.parseInt(tokens[i]);  //将数字字符串转化为整型数字
                stack.push(num);                      //若是数字则压栈  为计算符号则抛异常
            }catch(Exception e){
                int b=stack.pop();  //两个运算符前即将要计算的数字
                int a=stack.pop(); 
                stack.push(getCal(a,b,tokens[i]));
            }
        }
        return stack.pop();  //返回最终的结果
    }
    public int  getCal(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;
        }
    }  
}

以正常循环方式:

import java.util.Stack;
public class Solution{
    public int evalRPN(String [] tokens){
        if(tokens==null){
            return Integer.MAX_VALUE;
        }
        Stack<Integer> stack=new Stack<Integer> ();
        for(int i=0;i<tokens.length;i++){
            String s=tokens[i];
            if(s.equals("+") || s.equals("-")  || s.equals("*")|| s.equals("/")){  //比较内容相等 必须用equals
                int num2=stack.pop();
                int num1=stack.pop();
                int result=0;
                switch(s){
                    case "+":
                        result=num1+num2;     //必须在case分语句中设置break  或者直接return 数据
                        break;
                    case "-":
                        result=num1-num2;
                        break;
                    case "*":
                        result=num1*num2;
                        break;
                    case "/":
                        result=num1/num2;
                        break;
                    default:
                        result=0;
                }
                stack.push(result);
            }else{
                stack.push(Integer.parseInt(tokens[i]));
            }
        }
        return stack.pop();
    }
}






猜你喜欢

转载自blog.csdn.net/duoduo18up/article/details/79907765