Given a string, reverse only the vowels present in it and print the resulting string. example input: ransomware output: rensamwora
Here is my solution:
import java.util.Scanner;
public class ReversingVowels {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfTestCases = scanner.nextInt();
while (numberOfTestCases --> 0) {
StringBuilder stringWhoseVowelsShouldBeReversed = new StringBuilder(scanner.next());
System.out.println(reverseVowels(stringWhoseVowelsShouldBeReversed));
}
scanner.close();
}
private static String reverseVowels(StringBuilder string) {
if (string.length() == 0 || string.length() == 1) return string.toString();
int start = 0;
int end = string.length() - 1;
while (true) {
while (! isVowel(string.charAt(start))) {
start++;
}
while (! isVowel(string.charAt(end))) {
end--;
}
if (start >= end) {
break;
}
else {
swapVowels(string, start, end);
start++;
end--;
}
}
return string.toString();
}
private static boolean isVowel(char character) {
switch(character) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u': return true;
default: return false;
}
}
private static void swapVowels(StringBuilder string, int index1, int index2) {
char tmp = string.charAt(index1);
string.setCharAt(index1, string.charAt(index2));
string.setCharAt(index2, tmp);
}
}
Questions:
- Are there any bad practises
- Are there any issues
- Can this be improved