***、题目链接
一、题目
1、题目描述
给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。
假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。
注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。
返回词汇表 words 中你掌握的所有单词的 长度之和。
样例输入:words = ["cat","bt","hat","tree"], chars = "atach"
;
样例输出:6
。
2、基础框架
- C++给出的代码框架如下:
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
}
};
二、解题报告
1、思路分析
(
1
)
(1)
(1) 将 chars
和每个 words
的每个字母出现次数记录下来;
(
2
)
(2)
(2) 比较两个记录字母出现的字符串;
(
3
)
(3)
(3) 如果words
中存在字母在 chars
中没有出现过,或者 words
中存在字母出现个数大于 chars
中出现的个数,则跳过该单词;反之,对其长度累加。
2、时间复杂度
O ( n 2 ) O(n^2) O(n2) ,;
3、代码详解
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
vector<string> iter;
int sum = 0;
string tempChars = "00000000000000000000000000";
for(int i = 0; i < chars.size(); ++i){
tempChars[chars[i] - 'a'] ++;
}
for(auto &word : words){
bool isCan = true;
string tempWord = "00000000000000000000000000";
for(int i = 0; i < word.size(); ++i){
tempWord[word[i] - 'a'] ++;
}
for(int i = 0; i < word.size(); ++i){
if(tempChars[word[i] - 'a'] == '0' || tempWord[word[i] - 'a'] > tempChars[word[i] - 'a']){
isCan = false;
break;
}
}
if(isCan) sum += word.size();
}
return sum;
}
};
三、写在最后
核心思路是记录与比较,其实也可以用哈希表做,但现在是字符串专题,还是用字符串做吧,哈哈哈。