[LeetCode-JAVA] Basic Calculator

來源:互聯網
上載者:User

標籤:

題目:

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2" 2-1 + 2 " = 3"(1+(4+5+2)-3)+(6+8)" = 23

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

題意:設計一個簡易計算機,只有正數,運算子為"+" "-" "()" ,輸入為string,去掉無用的空格後,給定的算式一定是合法的

思路1(順序求解):為了將有括弧和無括弧的進行合并計算,認為的在string兩端加上一對(),方便計算,同時考慮都數字可能很多位,這時需要切分出每一個數字和符號,因此要設計兩個stack,分別存放數字和運算子,然後每當遇到右括弧的時候進行計算,由於正常的計算應該是自左向右,所以在計算的過程中,應該每一位進行計算,而不是彈出兩位進行計算。

例如: (2 - 1 + 2)

正確的計算順序為 + 2 - 1 最後char的stacj遇到左括弧 在 + 2

錯誤的計算書序為 1 + 2 結果存入a 之後再 2 - a 顯然是錯誤的 需要細細體會

最後istack中的數字即為結果。

代碼1:

public class Solution {    public int calculate(String s) {        if(s == null || s.length() == 0)            return 0;        s = "(" + s + ")";        Stack<Character> cstack = new Stack<Character>();        Stack<Integer> istack = new Stack<Integer>();                boolean isNum = false;        int sum = 0;                for(int i = 0 ; i < s.length() ; i++){            if(s.charAt(i) == ‘ ‘)                continue;            if(Character.isDigit(s.charAt(i))){                sum = sum *10 + s.charAt(i) - ‘0‘;                isNum = true;                continue;            }else if(isNum){  //考慮到會有 (( 連續的非數字情況 只需壓入一次數字                istack.push(sum);                sum = 0;                isNum = false;            }                        if(s.charAt(i) == ‘+‘ || s.charAt(i) == ‘-‘ || s.charAt(i) == ‘(‘){                cstack.push(s.charAt(i));            }else if(s.charAt(i) == ‘)‘){                int temp = 0;  // 每一次括弧裡的值                while(cstack.peek() != ‘(‘){  //直到可以匹配的左括弧                    int a = istack.pop();                    int c = cstack.pop();                    if(c == ‘+‘){                        temp += a;                    }else if(c == ‘-‘){                        temp -= a;                    }                }                temp += istack.pop(); // 加上左括弧後面的數字                istack.push(temp);                cstack.pop();            }        }                return istack.pop();    }}

思路2(尾碼運算式):通用的計算方式,將帶括弧的運算時轉化為 不帶括弧的尾碼運算式,之後用一個stack即可完成。

代碼2: (剛有思路,代碼debug中)...

[LeetCode-JAVA] Basic Calculator

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.