classSolution{publicintmaxNumberOfBalloons(String text){Map<Character,Integer> map =newHashMap();String target ="balloon";int res =0;// Count each characterfor(char c : text.toCharArray()){
map.put(c, map.getOrDefault(c,0)+1);}// Find ballonswhile(true){// iterate "balloon"for(char c : target.toCharArray()){// Until the character does not exist// or it's count is 0 alreadyif(map.get(c)==null|| map.get(c)==0)return res;// Update count
map.put(c, map.get(c)-1);}++res;}}}
Neetcode給出了另一個種思路
紀錄text和"balloon"的每個字母個數
疊代b a l l o o n,每次都取res或是text[c] // balloon[c]看誰比較小
簡單來說就是,如果b只有一個,那就不可能會湊成兩個以上balloon,除法就是為了看最多能湊幾個
classSolution{publicintmaxNumberOfBalloons(String text){HashMap<Character,Integer> balloon =newHashMap<>();HashMap<Character,Integer> countText =newHashMap<>();char[] balloonArray ="balloon".toCharArray();for(char c : balloonArray){if(balloon.containsKey(c)){
balloon.put(c,balloon.get(c)+1);}else{
balloon.put(c,1);}}char[] countTextArray = text.toCharArray();for(char c : countTextArray){if(countText.containsKey(c)){
countText.put(c,countText.get(c)+1);}else{
countText.put(c,1);}}int res = text.length();for(Character c : balloon.keySet()){
res =Math.min(res,countText.getOrDefault(c,0)/ balloon.get(c));}return res;}}