Back to Leetcode Go

345. Reverse Vowels of a String

website/content.en/ChapterFour/0300~0399/0345.Reverse-Vowels-of-a-String.md

1.7.971.1 KB
Original Source

345. Reverse Vowels of a String

Problem

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:


Input: "hello"
Output: "holle"

Example 2:


Input: "leetcode"
Output: "leotcede"

Problem Summary

The problem requires us to reverse the vowels in a string. Note that letter case matters.

Solution Approach

The solution approach for this problem is to use 2 pointers, the two-pointer collision approach, to continuously swap the elements at the beginning and end. This problem has the same approach as Problem 344.

Code

go
package leetcode

func reverseVowels(s string) string {
	b := []byte(s)
	for i, j := 0, len(b)-1; i < j; {
		if !isVowel(b[i]) {
			i++
			continue
		}
		if !isVowel(b[j]) {
			j--
			continue
		}
		b[i], b[j] = b[j], b[i]
		i++
		j--
	}
	return string(b)
}

func isVowel(s byte) bool {
	return s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u' || s == 'A' ||
		s == 'E' || s == 'I' || s == 'O' || s == 'U'
}