題目地址:
https://leetcode.com/problems/maximum-number-of-balloons/
給定一個字符串,問其中字母可以組成多少個單詞。
思路是直接數字符串裏含多少,然後從的出現次數取最小,再從的出現次數中除以後再取最小,兩個最小再取最小即爲答案。代碼如下:
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;
}
}
時空複雜度。
正確性證明可以用夾逼的辦法來證明,先證明不可能產生比更多的,再證明上面的方法可以產生可以產生個即可。