1 public class Solution { 2 public String reverseVowels(String s) { 3 if (s == null || s.length() < 2) { 4 return s; 5 } 6 7 StringBuilder result = new StringBuilder(); 8 int end = s.length() - 1; 9 for (int i = 0; i < s.length(); i++) { 10 if (isVowels(Character.toLowerCase(s.charAt(i)))) { 11 while (end >= 0 && !isVowels(Character.toLowerCase(s.charAt(end)))) { 12 end--; 13 } 14 result.append(s.charAt(end--)); 15 } else { 16 result.append(s.charAt(i)); 17 } 18 } 19 return result.toString(); 20 } 21 22 private boolean isVowels(char c) { 23 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; 24 } 25 }
DO NOT forget to move the end index one more. Otherwise, it will keep stucking in same vowel.