Re: [閒聊] 每日LeetCode

作者: ZooseWu (N5)   2023-12-02 15:10:21
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
}
作者: ILoveNTR (愛綠綠)   2023-12-02 15:11:00
大師
作者: oin1104 (是oin的說)   2023-12-02 15:18:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com