https://leetcode.com/problems/find-words-that-can-be-formed-by-characters/description/ | Easy |
---|
Дан массив строк words
и строка chars
. Строка считается "хорошей", если её можно сформировать из символов строки chars
(каждый символ можно использовать не чаще, чем он встречается в chars
). Верни сумму длин всех "хороших" строк из массива words
.
Input:
words = ["cat","bt","hat","tree"], chars = "atach”Output:
6Explanation:
Строки "cat" и "hat" можно собрать из символов "atach".
Input:
words = ["hello","world","leetcode"], chars = "welldonehoneyr”Output:
10Explanation:
"hello" и "world" подходят.
fun countCharacters(words: Array<String>, chars: String): Int {
val charsCount = IntArray(26)
for (c in chars) charsCount[c - 'a']++ // считаем доступные символы
var result = 0
wordLoop@ for (word in words) {
val wordCount = IntArray(26)
for (c in word) {
wordCount[c - 'a']++
if (wordCount[c - 'a'] > charsCount[c - 'a']) continue@wordLoop // символов не хватает
}
result += word.length // слово подходит, суммируем длину
}
return result
}
O(n * m), где n — количество слов, m — средняя длина слова.
O(1), память ограничена фиксированными массивами на 26 символов.