1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { public String reverseVowels(String s) { Character[] vowels = new Character[] { 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; Set<Character> vowelSet = new HashSet<>(); Collections.addAll(vowelSet, vowels); char[] sArray = s.toCharArray(); int left = 0, right = sArray.length - 1; while (left < right) { if (!vowelSet.contains(sArray[left])) { left += 1; continue; } if (!vowelSet.contains(sArray[right])) { right -= 1; continue; } swap(sArray, left, right); left += 1; right -= 1; } return new String(sArray); }
private void swap(char[] array, int i, int j) { char temp = array[i]; array[i] = array[j]; array[j] = temp; } }
|