Re: [閒聊] 每日LeetCode

看板Marginalman作者 (動物園 公告)時間1年前 (2023/11/13 02:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串510/719 (看更多)
2785. Sort Vowels in a String 給你一個字串 子音不動母音自己排序之後回傳 * 照著ASCII value排序 * 母音 = a e i o u Input: s = "lEetcOde" Output: "lEOtcede" Input: s = "lYmpH" Output: "lYmpH" Intuition 這題蠻簡單的 就是把字串的字母擷取出來後 排序在替換成新的就好 Approach 一開始先跑第一個迴圈 把所有母音的位置以及字元找出來 排序後再跑一次迴圈依序將字母填回去即可 後來看了別人的答案之後 發現字母數量很少 可以直接用一個陣列依序紀錄字母出現的次數之後填回去 少一個排序的動作可以把時間複雜度從 O(nlogn)降到O(n) TS Code: const vowelIndex = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"] const GetVowelIndex = (char: string): number => { switch (char) { case "A": return 0 case "E": return 1 case "I": return 2 case "O": return 3 case "U": return 4 case "a": return 5 case "e": return 6 case "i": return 7 case "o": return 8 case "u": return 9 default: return 0 } } function sortVowels (s: string): string { let ar = s.split('') const vowels = new Set<String>(vowelIndex) const indexes: number[] = [] const count: number[] = new Array(10).fill(0) for (let i = 0; i < ar.length; i++) { if (!vowels.has(ar[i])) continue indexes.push(i) count[GetVowelIndex(ar[i])]++ } let countIndex = 0 for (let i = 0; i < indexes.length; i++) { while (count[countIndex] === 0) { countIndex++ } ar.splice(indexes[i], 1, vowelIndex[countIndex]) count[countIndex]-- } return ar.join('') } -- Zoosewu Yoututbe顯示PTT推文 可以在各個網站追實況或Live時使用 預覽圖: https://i.imgur.com/ZhtXdAJ.png
https://i.imgur.com/WqbLNV3.png
完整介紹: https://github.com/zoosewu/PTTChatOnYoutube/tree/master/homepage 支援的網站: Youtube Twitch Holotools Niji-mado Holodex -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.229.33 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1699841478.A.B8C.html
文章代碼(AID): #1bKON6kC (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bKON6kC (Marginalman)