反转字符串中的元音字符
345 Reverse Vowels of a String (Easy)
Leetcode / 力扣
Given s = "leetcode", return "leotcede".
使用双指针,一个从头到尾遍历,一个从尾到头遍历,当两个指针都遍历到元音字母时,将他们交换。
private final static HashSet<Character> vowels = new HashSet<>( Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')); public String reverseVowels(String s) { if (s == null) return null; int i = 0, j = s.length() - 1; char[] result = new char[s.length()]; while (i <= j) { char ci = s.charAt(i); char cj = s.charAt(j); if (!vowels.contains(ci)) { result[i++] = ci; } else if (!vowels.contains(cj)) { result[j--] = cj; } else { result[i++] = cj; result[j--] = ci; } } return new String(result); }