Reverse Only the Vowels
Problem
Reverse the order of the vowels (a, e, i, o, u in lower or upper case) in the word. All other letters stay at their places.
Constraints
- 1 <= length <= 10^5
Examples
Input
hello
Output
holle
Solutions
Strings are immutable in all three languages, so we copy the letters to an array first. The two pointers skip every non-vowel and swap the vowels they find.
/*
* Problem : Process text.
* Input : One line of text.
* Output : The new word.
* Approach: Two pointers.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(String s) {
// Step 1: Work on a char array, so we can swap letters in place.
char[] letters = s.toCharArray();
int left = 0;
int right = letters.length - 1;
String vowels = "aeiouAEIOU";
while (left < right) {
// Step 2: Move the left pointer to the next vowel and the right pointer to the previous vowel.
while (left < right && vowels.indexOf(letters[left]) < 0) {
left++;
}
while (left < right && vowels.indexOf(letters[right]) < 0) {
right--;
}
// Step 3: Swap the two vowels and move both pointers inside.
char temporary = letters[left];
letters[left] = letters[right];
letters[right] = temporary;
left++;
right--;
}
return new String(letters);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- Why do we copy the string into an array?