2785. Sort Vowels in a String

Leetcode link

题目简介

题目要求我们在给定的一个字符串中,挑出其中的母音(包括大小写)然后按照 ASC2 排序后放回原来母音的位置,最后返回新的字符串

解题思路

首先我们要准备一个排序好的大小写母音表字符串 sortedVowels(这一步能帮我们省一个排序的时间复杂度)

然后我们再准备一个与上述母音表长度相等的数组 vowelsCount,数组的元素代表同下标 sortedVowels 母音的个数,先给每个元素置 0

接着我们遍历字符串 s,挑出所有的母音字母,并给 vowelsCount 中的对应元素加上母音出现次数

最后我们再遍历一次字符串 s,替换母音字母

Javascript

/**
 * @param {string} s
 * @return {string}
 */
var sortVowels = function(s) {
    const sortedVowels = 'AEIOUaeiou'
    const vowelsCount = new Array(sortedVowels.length).fill(0)
    const chars = s.split('')

    chars.forEach(c=> {
        const idx = sortedVowels.indexOf(c)
        if(idx > -1) {
            vowelsCount[idx]++
        }
    })

    let vowelsCountIdx = 0
    const res = chars.map(c => {
        if(sortedVowels.includes(c)) {
            while(vowelsCount[vowelsCountIdx] === 0) {
                vowelsCountIdx++
            }

            vowelsCount[vowelsCountIdx]--
            return sortedVowels[vowelsCountIdx]
        }
        return c
    })

    return res.join('')
};

results matching ""

    No results matching ""