1. 程式人生 > 其它 >[LeetCode] 1160. Find Words That Can Be Formed by Characters 拼寫單詞

[LeetCode] 1160. Find Words That Can Be Formed by Characters 拼寫單詞


You are given an array of stringswordsand a stringchars.

A string isgoodifit can be formed bycharacters fromchars(each charactercan only be used once).

Return the sum of lengths of all good strings inwords.

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. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length<= 100
  3. All strings contain lowercase English letters only.

這道題給了一個單詞陣列 words,還有一個字串 chars,定義了一種好字串,說是能由 chars 中的字母組成的單詞,限定每個字母只能使用一次,不必都使用,求所有好字串的長度之和。既然是 Easy 的身價,自然不會用到太 fancy 的解法,就是一個單純的字母統計問題,建立 chars 字串中每個字母和其出現次數之間的對映,然後遍歷每個單詞,拷貝一個 chars 字串的 HashMap,然後遍歷當前單詞的每個字母,對應字母的對映值減1,若為負數了,表示 chars 中缺少必要的單詞,標記為 false。若最終為 true,則將當前單詞的長度加入結果 res 中即可,參見程式碼如下:


class Solution {
public:
    int countCharacters(vector<string>& words, string chars) {
        int res = 0;
        unordered_map<char, int> charCnt;
        for (char c : chars) ++charCnt[c];
        for (string word : words) {
            unordered_map<char, int> m = charCnt;
            bool succeed = true;
            for (char c : word) {
                if (--m[c] < 0) {
                    succeed = false;
                    break;
                }
            }
            if (succeed) res += word.size();
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1160


參考資料:

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

https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/discuss/360978/C%2B%2B-Track-Count


LeetCode All in One 題目講解彙總(持續更新中...)