1160. Find Words That Can Be Formed by Characters
给你一个字串chars
还有一堆字串阵列words
检查words有多少字串可以由chars组合起来
回传所有可以组合起来的字串长度总和
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
"cat".length + "hat".length = 6
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr"
Output: 10
"hello".length + "world".length = 10
弄一个map
检查字符数量够不够就好了
TS Code:
const getCharCode = (char: string): number => (char.charCodeAt(0) - 97)
function countCharacters (words: string[], chars: string): number {
const target = chars.split('').reduce((arr, c) => {
arr[getCharCode(c)]++
return arr
}, new Array<number>(26).fill(0))
let result = 0
for (let i = 0; i < words.length; i++) {
const newArr: number[] = new Array(26).fill(0)
let isGood = true
for (let j = 0; j < words[i].length; j++) {
const code = getCharCode(words[i][j])
newArr[code]++
if (newArr[code] > target[code]) {
isGood = false
break
}
}
if (!isGood) continue
result += words[i].length
}
return result
}