標籤:
題目:
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