Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (動物園 公告)時間1年前 (2023/12/02 07:10), 編輯推噓2(200)
留言2則, 2人參與, 1年前最新討論串562/719 (看更多)
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

12/02 15:11, 1年前 , 1F
大師
12/02 15:11, 1F

12/02 15:18, 1年前 , 2F
大師
12/02 15:18, 2F
文章代碼(AID): #1bQjXVet (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bQjXVet (Marginalman)