LeetCode_p150_逆波蘭表達式計算/後綴表達式計算

有效的運算符包括 +, -, *, / 。每一個運算對象能夠是整數,也能夠是另外一個逆波蘭表達式。

說明:spa

  • 整數除法只保留整數部分。code

  • 給定逆波蘭表達式老是有效的。換句話說,表達式總會得出有效數值且不存在除數爲 0 的狀況。對象

示例 1:blog

輸入: ["2", "1", "+", "3", "*"]
輸出: 9
解釋: ((2 + 1) * 3) = 9

示例 2:token

輸入: ["4", "13", "5", "/", "+"]
輸出: 6
解釋: (4 + (13 / 5)) = 6

解題要點:字符串

  • 判斷一個字符串是不是數字。可能遇到的坑ast

    • 「-11」 也是一個數字class

    • 「-」 不是一個數字遍歷

     

  • 使用棧來解決此問題,首次彈出的第二個操做數,而後彈出的是第一個操做數。用這個實例判斷本身寫的是否正確:{"0","3","/"}di

解題思路:

遇到數字入棧,遇到操做符數字出棧進行運算,運算結果再次入棧,遍歷一次,棧中最後的那個數就是計算結果

源代碼

    public boolean isNum(String str){
        boolean result = false;
        char[] chars = str.toCharArray();
        for (int i = 0; i <chars.length; i++) {
            if(i==0 && chars[i]==45){
                continue;
           }
            if(chars[i]>=48 && chars[i]<=57){
                result = true;
           }
       }
        return  result;
   }
​
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new ArrayDeque<>();
        for(int i=0;i<tokens.length;i++){
            if(isNum(tokens[i])){
                stack.offer(Integer.parseInt(tokens[i]));
           }else {
                int second = stack.pollLast();
                int first = stack.pollLast();
                String tempStr = tokens[i];
                int tempResult=0;
                //判斷該符號
                if("+".equals(tempStr)){
                    tempResult=first+second;
               }else if("-".equals(tempStr)){
                    tempResult= first-second;
               }else if("*".equals(tempStr)){
                    tempResult= first*second;
               }else if("/".equals(tempStr)){
                    tempResult= first/second;
               }
                stack.offer(tempResult);
           }
       }
        return stack.pollLast();
   }
相關文章
相關標籤/搜索