题目描述
难度:简单
给你一份『词汇表』(字符串数组) 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
- 所有字符串中都仅包含小写英文字母
思路一——哈希表记数
遍历每个单词中的字母前,使用unordered_map记录字母表中的字母个数,便于查询。然后判断单词中的字母若在字母表存在且目前数量大于0,值减一;若不存在或为0则拼写失败。最后检查,若拼写成功则记录最大长度。
int countCharacters(vector<string>& words, string chars) {
unordered_map<char,int>map;
int maxLength=0;
for(int i=0;i<words.size();i++)
{
//初始化字母表
map.clear();
for(int i = 0;i<chars.length();i++)
{
auto it = map.find(chars[i]);
if(it!=map.end())
it->second++;
else
map.insert(make_pair(chars[i],1));
}
//拼写单词
int j;
for(j=0;j<words[i].length();j++)
{
auto it = map.find(words[i][j]);
if(it!=map.end() && it->second>0)//每个字母只能用一次
it->second--;
else
break;
}
if(j == words[i].length())//拼写成功
{
maxLength += words[i].length();
}
}
return maxLength;
}
思路二——官方哈希表记数
使用两个unordered_map进行比较,一个记录字母表中的字母数量,一个记录每个单词的字母数量。记录结束后,根据比较若单词的每个字母数量均≤字母表中的,即拼写成功。
int countCharacters(vector<string>& words, string chars) {
unordered_map<char,int>map;
int maxLength=0;
//初始化字母统计表
for(char c : chars)
map[c]++;
for(string word : words)
{
//单词字符统计表
unordered_map<char,int>wordMap;
for(char c : word)
wordMap[c]++;
//比较字母表和单词中字母的个数
bool canSpell = true;
for(auto it : wordMap)
if(wordMap[it.first] > map[it.first])
{//单词字母数多于字母表时
canSpell = false;
break;
}
if(canSpell)//拼写成功
maxLength += word.length();
}
return maxLength;
}