345. Reverse Vowels of a String
Asked at 13Google45Bloomberg43Microsoft42Amazon39Meta28Apple22EPAM Systems72tcs27Twitch69Deloitte50Oracle49Zoho42Visa39
Problem
Reverse only the vowels (a e i o u, either case) of s, leaving every other character where it is.
Example: "IceCreAm" → "AceCreIm"; "leetcode" → "leotcede"
Opposite-end pointers: advance each pointer past consonants, swap when both sit on vowels (either case).
Complexity: O(n).
class Solution:
def reverseVowels(self, s: str) -> str:
vowels = set("aeiouAEIOU")
a, i, j = list(s), 0, len(s) - 1
while i < j:
if a[i] not in vowels:
i += 1
elif a[j] not in vowels:
j -= 1
else:
a[i], a[j] = a[j], a[i]
i, j = i + 1, j - 1
return "".join(a)
assert Solution().reverseVowels("IceCreAm") == "AceCreIm"
assert Solution().reverseVowels("leetcode") == "leotcede"
assert Solution().reverseVowels("bcd") == "bcd"
assert Solution().reverseVowels("aA") == "Aa"
class Solution {
public String reverseVowels(String s) {
char[] a = s.toCharArray();
for (int i = 0, j = a.length - 1; i < j; ) {
if ("aeiouAEIOU".indexOf(a[i]) < 0) i++;
else if ("aeiouAEIOU".indexOf(a[j]) < 0) j--;
else { char t = a[i]; a[i++] = a[j]; a[j--] = t; }
}
return new String(a);
}
}
func reverseVowels(s string) string {
vowel := func(c byte) bool { return strings.IndexByte("aeiouAEIOU", c) >= 0 }
a := []byte(s)
for i, j := 0, len(a)-1; i < j; {
switch {
case !vowel(a[i]):
i++
case !vowel(a[j]):
j--
default:
a[i], a[j] = a[j], a[i]
i, j = i+1, j-1
}
}
return string(a)
}