-
題目描述:給你一份『詞彙表』(字符串數組) 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
所有字符串中都僅包含小寫英文字母 -
解析(轉載)
這是一類經典的題型。凡是和“變位詞”、“字母順序打亂”相關的題目,都考慮統計字母出現的次數。這種方法我叫做 “counter 方法”,因爲 Python 中有個 Counter 類就是專門用來計數的。我們既統計“字母表”中字母出現的次數,也統計單詞中字母出現的次數。如果單詞中每種字母出現的次數都小於等於字母表中字母出現的次數,那麼這個單詞就可以由字母表拼出來。整個過程如下圖所示:
-
題解(轉載)
class Solution { public int countCharacters(String[] words, String chars) { int[] chars_count = count(chars); // 統計字母表的字母出現次數 int res = 0; for (String word : words) { int[] word_count = count(word); // 統計單詞的字母出現次數 if (contains(chars_count, word_count)) { res += word.length(); } } return res; } // 檢查字母表的字母出現次數是否覆蓋單詞的字母出現次數 boolean contains(int[] chars_count, int[] word_count) { for (int i = 0; i < 26; i++) { if (chars_count[i] < word_count[i]) { return false; } } return true; } // 統計 26 個字母出現的次數 int[] count(String word) { int[] counter = new int[26]; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); counter[c-'a']++; } return counter; } } 作者:nettee 鏈接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/solution/tong-ji-zi-mu-chu-xian-de-ci-shu-shu-zu-ji-qiao-cj/ 來源:力扣(LeetCode) 著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
-
解題思路(轉載)
友情提示:遇到有提示字符串僅包含小寫(或者大寫)英文字母的題,
都可以試着考慮能不能構造長度爲26的每個元素分別代表一個字母的數組,來簡化計算對於這道題,用數組c來保存字母表裏每個字母出現的次數
如法炮製,再對詞彙表中的每個詞彙都做一數組w,比較數組w與數組c的對應位置如果w中的都不大於c,就說明該詞可以被拼寫出,長度計入結果
如果w其中有一個超過了c,則說明不可以被拼寫,直接跳至下一個(這裏用到了帶label的continue語法)作者:pendygg
鏈接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters/solution/ji-de-di-yi-ci-kan-bie-ren-yong-int26de-shi-hou-be/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-words-that-can-be-formed-by-characters
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。