[LeetCode-JAVA] Basic Calculator II

來源:互聯網
上載者:User

標籤:

題目:

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7" 3/2 " = 1" 3+5 / 2 " = 5

 

Note: Do not use the eval built-in library function.

題意:簡易計算機,可以進行四則運算

思路:在I的基礎上可以很清晰的分析此題,利用兩個Stack,一個儲存數字,一個儲存符號需要注意一下幾點:

 (1)連續的數字需要進行處理;

 (2)乘除需要在後一個數字入棧後處理;

 (3)最後棧內剩餘為加減法,只需要一步步彈出即可,需要記住一次只彈出一個數字和符號,不能兩個數字運算,在I中有說明,遺忘的話可以點擊->  Basic Calculator I

 (4)需要對最後一個數字進行特殊處理,因為前面的方法只有檢測到有符號的時候才會將數字如棧。

代碼(後面有最佳化版):

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0)            return 0;        Stack<Integer> num = new Stack<Integer>();        Stack<Character> symbol = new Stack<Character>();                boolean isNum = false;        int count = 0;        for(int i = 0 ; i < s.length() ; i++){            if(s.charAt(i) == ‘ ‘)                continue;            char temp = s.charAt(i);            if(Character.isDigit(temp)){                count = count * 10 + (temp - ‘0‘) ;                isNum = true;            }else if(isNum){                num.push(count);                count = 0;                isNum = false;                if(!symbol.isEmpty() && (symbol.peek() == ‘*‘ || symbol.peek() == ‘/‘)){                    char tempSymbol = symbol.pop();                    int b = num.pop();                    int a = num.pop();                    if(tempSymbol == ‘*‘){                        num.push(a*b);                    }else{                        num.push(a/b);                    }                }            }            if(!Character.isDigit(temp)){                symbol.push(temp);            }        }        if(isNum){            num.push(count);            if(!symbol.isEmpty() && (symbol.peek() == ‘*‘ || symbol.peek() == ‘/‘)){                char tempSymbol = symbol.pop();                int b = num.pop();                int a = num.pop();                if(tempSymbol == ‘*‘){                    num.push(a*b);                }else{                    num.push(a/b);                }            }        }                if(!symbol.isEmpty()){            int rep = 0;            while(!symbol.isEmpty()){                char tempSymbol = symbol.pop();                int a = num.pop();                if(tempSymbol == ‘+‘){                    rep+=a;                }else{                    rep-=a;                }            }            num.push(rep + num.pop());        }                return num.pop();    }}

 

最佳化思路:注意到代碼有冗餘的部分,是因為每一次數字入棧是在判斷有符號的時候,這時,可以人為的在初始出入的String的末尾加入非運算子號,這樣可以將二者整合到一起。

最佳化後代碼:

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0)            return 0;        Stack<Integer> num = new Stack<Integer>();        Stack<Character> symbol = new Stack<Character>();        s += "#";        boolean isNum = false;        int count = 0;        for(int i = 0 ; i < s.length() ; i++){            if(s.charAt(i) == ‘ ‘)                continue;            char temp = s.charAt(i);            if(Character.isDigit(temp)){                count = count * 10 + (temp - ‘0‘) ; // 連續的數字                isNum = true;            }else{                if(isNum){  // 遇到符號 將前面數字壓入                    num.push(count);                    count = 0;                    isNum = false;                    if(!symbol.isEmpty() && (symbol.peek() == ‘*‘ || symbol.peek() == ‘/‘)){                        char tempSymbol = symbol.pop();                        int b = num.pop();                        int a = num.pop();                        if(tempSymbol == ‘*‘){                            num.push(a*b);                        }else{                            num.push(a/b);                        }                    }                }                if(temp != ‘#‘){ // 將符號壓入                    symbol.push(temp);                }            }        }                if(!symbol.isEmpty()){            int rep = 0;            while(!symbol.isEmpty()){  // 加減運算                char tempSymbol = symbol.pop();                int a = num.pop();                if(tempSymbol == ‘+‘){                    rep+=a;                }else{                    rep-=a;                }            }            num.push(rep + num.pop());        }                return num.pop();    }}

 

[LeetCode-JAVA] Basic Calculator II

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.