题目

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:

  1. Input: "hello"
  2. Output: "holle"

Example 2:

  1. Input: "leetcode"
  2. Output: "leotcede"

Note:
The vowels does not include the letter “y”.


题意

只将字符串中的元音字母逆置。

思路

Two Pointers。只将元音字母两两交换。


代码实现

Java

  1. class Solution {
  2. public String reverseVowels(String s) {
  3. char[] array = s.toCharArray();
  4. Set<Character> set = Set.of('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U');
  5. int left = 0, right = s.length() - 1;
  6. while (left < right) {
  7. while (left < right && !set.contains(array[left])) {
  8. left++;
  9. }
  10. while (left < right && !set.contains(array[right])) {
  11. right--;
  12. }
  13. if (left < right) {
  14. char tmp = array[left];
  15. array[left++] = array[right];
  16. array[right--] = tmp;
  17. }
  18. }
  19. return new String(array);
  20. }
  21. }