Re: [閒聊] 每日LeetCode

看板 Marginalman
作者 ZooseWu (動物園 公告)
時間 2023-12-02 15:10:21
留言 0則留言 (0推 0噓 0→)

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 } --
※ 批踢踢實業坊(ptt.cc), 來自: 114.32.229.33 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1701501023.A.A37.html

您可能感興趣