Find Words That Can Be Formed by Characters
Problem statement
You are given an array of strings words and a string chars.
A word is good when it can be spelled using letters taken from chars, where each letter of chars can be used at most once in that word. Every word is checked on its own against all of chars: using letters for one word does not use them up for another word.
Return the sum of the lengths of all good words. A word that appears more than once in words counts each time it appears.
Function
countCharacters(words: String[], chars: String) → intExamples
Example 1
words = ["pay","tab","apply","bat"]chars = "tapbay"return = 9chars has the letters t, a, p, b, a and y. "pay", "tab" and "bat" can each be spelled from them, because every word is checked against the full set of letters on its own. "apply" needs two p and an l, but chars has one p and no l. The answer is 3 + 3 + 3 = 9.
Example 2
words = ["noon","on","moon"]chars = "onon"return = 6chars has two o and two n. "noon" uses all four letters and "on" uses two, so both are good. "moon" needs an m, which chars does not have. The answer is 4 + 2 = 6.
Example 3
words = ["zz"]chars = "z"return = 0"zz" needs two copies of z, but chars has only one. Each letter of chars can be used at most once in a word, so no word is good and the answer is 0.
Constraints
1 <= words.length <= 10001 <= words[i].length <= 1001 <= chars.length <= 100words[i]andcharscontain only lowercase English letters.