leetcode 1160. 拼写单词
题目详情
题目链接
给你一份『词汇表』(字符串数组) 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
所有字符串中都仅包含小写英文字母
我的代码
class Solution {
public:
int getWordSize(map<char, int> letters, string word) {
for (char letter: word) {
if ((letters.count(letter) == 0) || (letters[letter] == 0)) {
return 0;
}
--letters[letter];
}
return word.size();
}
int countCharacters(vector<string>& words, string chars) {
map<char, int> letters;
for (char letter: chars) {
letters[letter] = letters.count(letter) == 0? 1: letters[letter] + 1;
}
int res = 0;
for (string word: words) {
if (chars.size() < word.size()) {
continue;
}
res += getWordSize(letters, word);
}
return res;
}
};
我的成绩
执行结果:通过
执行用时 : 188 ms, 在所有 C++ 提交中击败了23.02%的用户
内存消耗 : 43.9 MB, 在所有 C++ 提交中击败了29.35%的用户
一些想法
- 我的想法是将chars中的字符作为一个map,记录每个字符出现的个数,方便查找,但效果看来并不是很好。
- 仔细想象,map可以用一个长度为26的数组来代替,节约空间和时间。
改进代码
class Solution {
public:
int getWordSize(vector<int> letters, string word) {
for (char letter: word) {
if (letters[letter - 'a'] == 0) {
return 0;
}
--letters[letter - 'a'];
}
return word.size();
}
int countCharacters(vector<string>& words, string chars) {
vector<int> letters(26, 0);
for (char letter: chars) {
++letters[letter - 'a'];
}
int res = 0;
for (string word: words) {
if (chars.size() < word.size()) {
continue;
}
res += getWordSize(letters, word);
}
return res;
}
};
改进后成绩
执行结果:通过
执行用时 : 92 ms, 在所有 C++ 提交中击败了49.88%的用户
内存消耗 : 21.5 MB, 在所有 C++ 提交中击败了45.65%的用户
执行用时为 28 ms 的范例
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
int charList[26]={0};
int res=0;
for (char ch : chars)
{
charList[ch-'a']++;
}
for (vector<string>::iterator it = words.begin(); it != words.end(); it++)
{
std::ios::sync_with_stdio(false);
int tmpCharList[26];
copy(charList,charList+26,tmpCharList);
int tar;
for (tar=0;tar<(*it).size();tar++)
{
tmpCharList[(*it)[tar]-'a']--;
if(tmpCharList[(*it)[tar]-'a']<0){
break;
}
}
if(tar==(*it).size()){
res+=(*it).size();
}
}
return res;
}
};
思考
范例解法和我改进后的代码类似,只不过没有使用函数。