1160. Find Words That Can Be Formed by Characters

1160. Find Words That Can Be Formed by Characters #

Problem #

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. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. All strings contain lowercase English letters only.

Problem Summary #

You are given a “vocabulary list” (string array) words and an “alphabet” (string) chars. If you can use the “letters” (characters) in chars to spell a certain “word” (string) in words, then we consider that you have mastered this word. Note: each time you spell a word, each letter in chars can only be used once. Return the sum of the lengths of all words in the vocabulary list words that you have mastered.

Constraints:

  1. 1 <= words.length <= 1000
  2. 1 <= words[i].length, chars.length <= 100
  3. All strings contain only lowercase English letters

Solution Approach #

  • Given a string array words and a string chars, output the total number of characters of the strings in words that can be formed by chars.
  • Easy problem. First count the frequency of characters in words and chars respectively. Then, for each word in words, determine whether it can be formed by chars; if it can, add the length of this word to the final result.

Code #


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
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文