Post

Leetcode - 345. Reverse Vowels of a String

Leetcode - 345. Reverse Vowels of a String

Hits

  • Given a string s, reverse only all the vowels in the string and return it.

    The vowels are ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’, and they can appear in both lower and upper cases, more than once.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func reverseVowels(s string) string {
    	// as we will replace inplace and strings are immutable in go, hence we converted them to rune
	strToRunes := []rune(s)
	firstInd, lastInd := 0, len(strToRunes)-1

	vowels := "aeiouAEIOU"

	for firstInd < lastInd{
		for firstInd<lastInd && !strings.ContainsRune(vowels, strToRunes[firstInd]){
				firstInd++
			}

		for firstInd<lastInd && !strings.ContainsRune(vowels, strToRunes[lastInd]){
				lastInd--
			}

		strToRunes[firstInd], strToRunes[lastInd] = strToRunes[lastInd], strToRunes[firstInd]
		firstInd++
		lastInd--
	}

	return string(strToRunes) 
}

This post is licensed under CC BY 4.0 by the author.