Skip to content

Commit 55f4c04

Browse files
authored
Update Maximum Number of Balloons.java
1 parent 649978e commit 55f4c04

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

Easy/Maximum Number of Balloons.java

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
class Solution {
2-
public int maxNumberOfBalloons(String text) {
3-
Map<Character, Integer> map = new HashMap<>();
4-
for (Character c : text.toCharArray()) {
5-
map.put(c, map.getOrDefault(c, 0) + 1);
6-
}
7-
int maxCount = 0;
8-
maxCount = map.getOrDefault('l', 0) / 2;
9-
maxCount = Math.min(map.getOrDefault('o', 0) / 2, maxCount);
10-
maxCount = Math.min(map.getOrDefault('b', 0), maxCount);
11-
maxCount = Math.min(map.getOrDefault('a', 0), maxCount);
12-
maxCount = Math.min(map.getOrDefault('n', 0), maxCount);
13-
return maxCount;
14-
}
2+
public int maxNumberOfBalloons(String text) {
3+
Map<Character, Long> textFrequencyMap = getFrequencyMap(text);
4+
Map<Character, Long> ballonFrequencyMap = getFrequencyMap("balloon");
5+
return ballonFrequencyMap.keySet().stream()
6+
.map(k ->
7+
(int) (textFrequencyMap.getOrDefault(k, 0L) / ballonFrequencyMap.get(k)))
8+
.min(Integer::compare)
9+
.orElse(0);
10+
}
11+
12+
private Map<Character, Long> getFrequencyMap(String s) {
13+
return s.chars()
14+
.mapToObj(c -> (char) c)
15+
.collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting()));
16+
}
1517
}

0 commit comments

Comments
 (0)