1160. Find Words That Can Be Formed by Characters*

​https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/​

题目描述

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 containlowercaseEnglish letters only.

C++ 实现 1

统计 ​​chars​​​ 中每个字符的个数, 判断 ​​words​​​ 中的每个 ​​string​​​ 是否可以使用 ​​chars​​ 中的字符生成.

class Solution {
private:
// 注意这里的 nums 不是引用, 会发生数据的拷贝, 从而不影响 records 数组
bool isGood(vector<int> nums, const string &str) {
for (auto &c : str) {
if (nums[c - 'a'] == 0) return false;
else nums[c - 'a'] --;
}
return true;
}
public:
int countCharacters(vector<string>& words, string chars) {
vector<int> records(26, 0);
int res = 0;
for (auto &c : chars) records[c - 'a'] ++;
for (auto &s : words)
if (isGood(records, s))
res += s.size();
return res;
}
};