LeetCode - 1160.拼写单词(哈希表)
题目:
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
示例 1:
输入:words = [“cat”,“bt”,“hat”,“tree”], chars = “atach”
输出:6
解释:
可以形成字符串 “cat” 和 “hat”,所以答案是 3 + 3 = 6。
示例 2:
输入:words = [“hello”,“world”,“leetcode”], chars = “welldonehoneyr”
输出:10
解释:
可以形成字符串 “hello” 和 “world”,所以答案是 5 + 5 = 10。
提示:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
所有字符串中都仅包含小写英文字母
方法一:
统计“字母表”中字母出现的次数,也统计单词中字母出现的次数。如果单词中每种字母出现的次数都小于等于字母表中字母出现的次数,那么这个单词就可以由字母表拼出来
class Solution {
public int countCharacters(String[] words, String chars) {
if(words.length == 0) return 0;
Map<Character,Integer> charCnt = new HashMap<Character, Integer>();
int length = chars.length();
for (int i = 0; i < length; i++) {
char c = chars.charAt(i);
charCnt.put(c,charCnt.getOrDefault(c,0) + 1);
}
int ans = 0;
for (String word : words) {
Map<Character,Integer> wordCnt = new HashMap<>();
int wordLength = word.length();
for (int i = 0; i < wordLength; i++) {
char c = word.charAt(i);
wordCnt.put(c,wordCnt.getOrDefault(c,0) + 1);
}
boolean isAns = true;
for (int i = 0; i < wordLength; i++) {
char c = word.charAt(i);
if (charCnt.getOrDefault(c,0) < wordCnt.getOrDefault(c,0)){
isAns = false;
break;
}
}
if (isAns){
ans += word.length();
}
}
return ans;
}
}
public int countCharacters(String[] words, String chars) {
int[] chars_count = count(chars); // 统计字母表的字母出现次数
int res = 0;
for (String word : words) {
int[] word_count = count(word); // 统计单词的字母出现次数
if (contains(chars_count, word_count)) {
res += word.length();
}
}
return res;
}
// 检查字母表的字母出现次数是否覆盖单词的字母出现次数
boolean contains(int[] chars_count, int[] word_count) {
for (int i = 0; i < 26; i++) {
if (chars_count[i] < word_count[i]) {
return false;
}
}
return true;
}
// 统计 26 个字母出现的次数
int[] count(String word) {
int[] counter = new int[26];
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
counter[c-'a']++;
}
return counter;
}
方法二:
遇到有提示字符串仅包含小写(或者大写)英文字母的题,
都可以试着考虑能不能构造长度为26的每个元素分别代表一个字母的数组,来简化计算
对于这道题,用数组c来保存字母表里每个字母出现的次数
如法炮制,再对词汇表中的每个词汇都做一数组w,比较数组w与数组c的对应位置
如果w中的都不大于c,就说明该词可以被拼写出,长度计入结果
如果w其中有一个超过了c,则说明不可以被拼写,直接跳至下一个(这里用到了带label的continue语法)
class Solution {
public int countCharacters(String[] words, String chars) {
int[] c = new int[26];
for(char cc : chars.toCharArray()) {
c[(int)(cc - 'a')] += 1;
}
int res = 0;
a: for(String word : words) {
int[] w = new int[26];
for(char ww : word.toCharArray()) {
w[(int)(ww - 'a')] += 1;
}
for(int i=0; i<26; i++) {
if(w[i] > c[i]) {
continue a;
}
}
res += word.length();
}
return res;
}
}