題目
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 <= 10001 <= words[i].length, chars.length <= 100- All strings contain lowercase English letters only.
題目大意
給你一份『詞彙表』(字符串數組) words 和一張『字母表』(字符串) chars。假如你可以用 chars 中的『字母』(字符)拼寫出 words 中的某個『單詞』(字符串),那麼我們就認為你掌握了這個單詞。注意:每次拼寫時,chars 中的每個字母都只能用一次。返回詞彙表 words 中你掌握的所有單詞的 長度之和。
提示:
- 1 <= words.length <= 1000
- 1 <= words[i].length, chars.length <= 100
- 所有字符串中都僅包含小寫英文字母
解題思路
- 給出一個字符串數組
words和一個字符串chars,要求輸出chars中能構成words字符串的字符數總數。 - 簡單題。先分別統計
words和chars裏面字符的頻次。然後針對words中每個word判斷能夠能由chars構成,如果能構成,最終結果加上這個word的長度。 ��這個word的長度。
參考代碼
package leetcode
func countCharacters(words []string, chars string) int {
count, res := make([]int, 26), 0
for i := 0; i < len(chars); i++ {
count[chars[i]-'a']++
}
for _, w := range words {
if canBeFormed(w, count) {
res += len(w)
}
}
return res
}
func canBeFormed(w string, c []int) bool {
count := make([]int, 26)
for i := 0; i < len(w); i++ {
count[w[i]-'a']++
if count[w[i]-'a'] > c[w[i]-'a'] {
return false
}
}
return true
}