题目地址:
https://leetcode.com/problems/maximum-number-of-balloons/
给定一个字符串,问其中字母可以组成多少个单词 b a l l o o n balloon balloon。
思路是直接数字符串里含多少 b , a , l , o , n b,a,l,o,n b,a,l,o,n,然后从 b , a , n b,a,n b,a,n的出现次数取最小,再从 l , o l,o l,o的出现次数中除以 2 2 2后再取最小,两个最小再取最小即为答案。代码如下:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int maxNumberOfBalloons(String text) {
Map<Character, Integer> map = new HashMap<>();
map.put('b', 0);
map.put('a', 0);
map.put('l', 0);
map.put('o', 0);
map.put('n', 0);
for (int i = 0; i < text.length(); i++) {
if (map.containsKey(text.charAt(i))) {
map.put(text.charAt(i), map.get(text.charAt(i)) + 1);
}
}
int res = Integer.MAX_VALUE;
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
char c = entry.getKey();
if (c == 'b' || c == 'a' || c == 'n') {
res = Math.min(res, entry.getValue());
} else {
res = Math.min(res, entry.getValue() / 2);
}
}
return res;
}
}
时空复杂度 O ( n ) O(n) O(n)。
正确性证明可以用夹逼的办法来证明,先证明不可能产生比 r e s res res更多的 b a l l o o n balloon balloon,再证明上面的方法可以产生可以产生 r e s res res个即可。