题目
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"Output: "holle"
Example 2:
Input: "leetcode"Output: "leotcede"
Note:
The vowels does not include the letter “y”.
题意
只将字符串中的元音字母逆置。
思路
Two Pointers。只将元音字母两两交换。
代码实现
Java
class Solution {public String reverseVowels(String s) {char[] array = s.toCharArray();Set<Character> set = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');int left = 0, right = s.length() - 1;while (left < right) {while (left < right && !set.contains(array[left])) {left++;}while (left < right && !set.contains(array[right])) {right--;}if (left < right) {char tmp = array[left];array[left++] = array[right];array[right--] = tmp;}}return new String(array);}}
