題目描述
難度:簡單
給你一份『詞彙表』(字符串數組) 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;
}