题目描述:
给你一份『词汇表』(字符串数组) 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
所有字符串中都仅包含小写英文字母
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
只想到了使用HashMap来解决,将chars中一一映射将个数保存在map中,然后循环遍历放入words中的单词,之后判断个数
代码
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
class Solution {
public int countCharacters(String[] words, String chars) {
Map<Character, Integer> map = new HashMap<>();
for (char string : chars.toCharArray()) {
map.put(string, map.getOrDefault(string, 0) + 1);
}
int result = 0;
for (String string : words) {
Map<Character, Integer> temMap = new HashMap<>();
for (char string2 : string.toCharArray()) {
temMap.put(string2, temMap.getOrDefault(string2, 0) + 1);
}
boolean flag = false;
for (Entry<Character, Integer> string2 : temMap.entrySet()) {
if(map.getOrDefault(string2.getKey(), 0) < string2.getValue()){
flag = true;
break;
}
}
if(!flag){
result += string.length();
}
}
return result;
}
}
排名靠前的代码
由于都是小写的字母,因此可以考虑只使用长度未26的数组,比单纯的HashMap遍历要快很多
class Solution {
private int[] charsCount = new int[26];
private int charsLength;
public int countCharacters(String[] words, String chars) {
charsLength = chars.length();
for (char c : chars.toCharArray()) {
charsCount[c - 'a']++;
}
int num = 0;
for (String str : words) {
num += getNum(str);
}
return num;
}
public int getNum(String str){
if(str.length() > charsLength){
return 0;
}
int[] strCount = new int[26];
for (char c : str.toCharArray()) {
if(strCount[c - 'a'] == charsCount[c - 'a'])
return 0;
else strCount[c - 'a']++;
}
return str.length();
}
}