Find Words That Can Be Formed by Characters
LeetCode 1160 · View on LeetCode
Sum the lengths of all words that can be formed using the available characters (each character used at most once per word).
package main
import (
"fmt"
"maps"
)
func countCharacters(words []string, chars string) int {
charsMap := map[rune]int{}
for _, ch := range chars {
charsMap[ch]++
}
length := 0
for _, w := range words {
mapClone := maps.Clone(charsMap)
found := true
for _, ch := range w {
if mapClone[ch] > 0 {
mapClone[ch]--
} else {
found = false
break
}
}
if found {
length += len(w)
}
}
return length
}
func main() {
words := []string{"cat", "bt", "hat", "tree"}
chars := "atach"
fmt.Println(countCharacters(words, chars)) // 6 ("cat" + "hat")
}Key idea: Clone the frequency map for each word so one word's consumption doesn't affect the next. Break early if any character is unavailable.