标签:tac 字符 建模 哈希 += c++ 判断 map you
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation:
The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
Explanation:
The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Note:
1 <= words.length <= 1000
1 <= words[i].length, chars.length <= 100
All strings contain lowercase English letters only.
常规题目,记下来主要是为了提醒自己。
一是审题,一开始认为是chars里面的字母对于所有word只能使用一次,结果是一个word只能使用一次。
二是实现,思路都是map,但是提交后看别人的,恍然大悟。原来可以自己构造哈希表。也不是什么稀罕的思路,只是遇到这个问题时自己没想到。
为什么?还不是建模的角度,对问题思考的深度。只有26种字母这点被忽略带来的就是我的执行时间是900+ms
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
map<char,int> charsMap;
int howmany=0;
for (int i=0;i<chars.size();i++)
if (charsMap.find(chars[i])==charsMap.end())
charsMap[chars[i]]=1;
else
charsMap[chars[i]]++;
for (auto it=words.begin();it!=words.end();it++){
map<char,int> wordsMap;
for (int i=0;i<(*it).size();i++)
if (wordsMap.find((*it)[i])==wordsMap.end())
wordsMap[(*it)[i]]=1;
else
wordsMap[(*it)[i]]++;
bool isContain=true;
int tmpCnt=0;
for (auto t=wordsMap.begin();t!=wordsMap.end();t++){
if (charsMap.find(t->first)==charsMap.end() ||
charsMap[t->first] < t->second){
isContain=false;
break;
}
else
tmpCnt+=t->second;
}
if (isContain)
howmany+=tmpCnt;
}
return howmany;
}
};
好像到现在还从来没看过题目下面的Note?
1160.Find Words That Can Be Formed By Characters
标签:tac 字符 建模 哈希 += c++ 判断 map you
原文地址:https://www.cnblogs.com/katachi/p/12589846.html