Go•find-words-that-can-be-formed-by-characters/solution.go
package main
func countCharacters(words []string, chars string) int {
var available [26]int
for _, character := range chars {
available[character-'a']++
}
total := 0
for _, word := range words {
var count [26]int
for _, character := range word {
count[character-'a']++
}
valid := true
for index, needed := range count {
if needed > available[index] {
valid = false
break
}
}
if valid {
total += len(word)
}
}
return total
}
Python•find-words-that-can-be-formed-by-characters/solution.py
from collections import Counter
class Solution:
def countCharacters(self, words: list[str], chars: str) -> int:
available = Counter(chars)
return sum(len(word) for word in words if not (Counter(word) - available))
TypeScript•find-words-that-can-be-formed-by-characters/solution.ts
function countCharacters(words: string[], chars: string): number {
const available = new Array<number>(class="syntax-number">26).fill(class="syntax-number">0); for (const character of chars) available[character.charCodeAt(class="syntax-number">0) - class="syntax-number">97] += class="syntax-number">1;
let total = class="syntax-number">0;
for (const word of words) { const count = new Array<number>(class="syntax-number">26).fill(class="syntax-number">0); for (const character of word) count[character.charCodeAt(class="syntax-number">0) - class="syntax-number">97] += class="syntax-number">1; if (count.every((needed, index) => needed <= available[index])) total += word.length; }
return total;
}