publicclassReverseVowelsofaString{ /** * Write a function that takes a string as input and reverse only the vowels of a string. * <p> * Example 1: * <p> * Input: "hello" * Output: "holle" * Example 2: * <p> * Input: "leetcode" * Output: "leotcede" */ public String reverseVowels(String s){ HashSet<Character> vowels = new HashSet<>(); char[] sc = s.toCharArray(); vowels.add('a'); vowels.add('e'); vowels.add('i'); vowels.add('o'); vowels.add('u'); int left = 0; int right = s.length() - 1; while (left < right) { if (vowels.contains(sc[left]) && vowels.contains(sc[right])) { char t = sc[left]; sc[left] = sc[right]; sc[right] = t; } if (!vowels.contains(sc[left])) left++; if (!vowels.contains(sc[right])) right--; } StringBuilder sb = new StringBuilder(); for (char c: sc){ sb.append(c); } return sb.toString(); } }