“气球”的最大数量
题目描述
“气球”的最大数量
思路
统计
统计balloon各个字母在text中出现的次数,其中l和o因为需要在一个单词中出现两次,所以统计时需要除以2。统计完找到各个字母出现次数最少的一个,它的次数就是balloon单词出现的次数。
Python实现
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
cnt = Counter(c for c in text if c in 'balon')
cnt['l'] //= 2
cnt['o'] //= 2
return min(cnt.values()) if len(cnt) == 5 else 0
Java实现
class Solution {
public int maxNumberOfBalloons(String text) {
int[] cnt = new int[5];
for (int i = 0; i < text.length(); ++i) {
char c = text.charAt(i);
if (c == 'b') {
cnt[0]++;
} else if (c == 'a') {
cnt[1]++;
} else if (c == 'l') {
cnt[2]++;
} else if (c == 'o') {
cnt[3]++;
} else if (c == 'n') {
cnt[4]++;
}
}
cnt[2] /= 2;
cnt[3] /= 2;
return Arrays.stream(cnt).min().getAsInt();
}
}