Reverse Vowels of a String
Problem
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 cases.
s = "lighthouse""leghthuosi"def reverse_vowels(s):
v = set("aeiouAEIOU")
a = list(s)
l, r = 0, len(a) - 1
while l < r:
while l < r and a[l] not in v: l += 1
while l < r and a[r] not in v: r -= 1
a[l], a[r] = a[r], a[l]; l += 1; r -= 1
return "".join(a)
function reverseVowels(s) {
const v = "aeiouAEIOU";
const a = s.split("");
let l = 0, r = a.length - 1;
while (l < r) {
while (l < r && !v.includes(a[l])) l++;
while (l < r && !v.includes(a[r])) r--;
[a[l], a[r]] = [a[r], a[l]]; l++; r--;
}
return a.join("");
}
class Solution {
public String reverseVowels(String s) {
String v = "aeiouAEIOU";
char[] a = s.toCharArray();
int l = 0, r = a.length - 1;
while (l < r) {
while (l < r && v.indexOf(a[l]) == -1) l++;
while (l < r && v.indexOf(a[r]) == -1) r--;
char tmp = a[l]; a[l] = a[r]; a[r] = tmp; l++; r--;
}
return new String(a);
}
}
string reverseVowels(string s) {
string v = "aeiouAEIOU";
int l = 0, r = (int)s.size() - 1;
while (l < r) {
while (l < r && v.find(s[l]) == string::npos) l++;
while (l < r && v.find(s[r]) == string::npos) r--;
swap(s[l], s[r]); l++; r--;
}
return s;
}
Explanation
We only want to move the vowels around and leave every consonant exactly where it is. The neat trick is to use two pointers that walk toward each other from opposite ends and swap vowels as they meet.
One pointer l starts on the left, the other r on the right. We keep a set v of all vowels (both cases) so checking "is this a vowel?" is instant. The inner loops skip any non-vowel: l moves right past consonants and r moves left past consonants.
When both pointers have landed on a vowel, we swap them with a[l], a[r] = a[r], a[l] and then step both inward. Because each vowel from the left is paired with the matching vowel from the right, the whole set of vowels ends up reversed while consonants never move.
Example: s = "lighthouse". The vowels in order are i, o, u, e. Pairing ends inward swaps i with e, then o with u, giving the vowel order e, u, o, i in the same slots, so the result is "leghthuosi".
Each character is looked at once as a pointer passes it, so this runs in a single pass over the string.