Re: [閒聊] 每日LeetCode
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://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
討論串 (同標題文章)
以下文章回應了本文 (最舊先):
完整討論串 (本文為第 510 之 719 篇):