LeetCode-1160——拼写单词

拼写单词(简单)

题目要求

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

​ 注意:每次拼写时,chars 中的每个字母都只能用一次。

​ 返回词汇表 words 中你掌握的所有单词的 长度之和。

​ 示例

1
2
3
4
5
6
7
8
9
输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释:
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。

输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。

通过数组计数

思路

​ 通过记录每个字符出现的次数,在遍历两个字符串后即可确定结果

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int countCharacters(vector<string>& words, string chars) {
vector<int> a(26, 0);
int ans=0;
for (int i = 0; i < chars.length(); i++)
a[chars[i] - 'a']++;
for (int i = 0; i < words.size(); i++) {
vector<int> a1 = a;
int j;
for (j = 0; j < words[i].length(); j++) {
a1[words[i][j] - 'a']--;
if (a1[words[i][j] - 'a'] == -1)
break;
}
if(j==words[i].length())ans+=words[i].length();
}
return ans;
}
};

思路

​ 先遍历一遍字母表字符串,用长度为 26 的数组来记录每个字母出现的次数,再通过遍历单词表中的每一个字母,出现一次就在数组中的数量上 -1,如果数量出现 -1,就不能组成这个单词,否则就可以继续寻找下去,最后返回结果

-------------本文结束感谢您的阅读-------------