LeetCode 345. Reverse Vowels of a String

345. Reverse Vowels of a String(反转字符串中的元音字母)

链接

https://leetcode-cn.com/problems/reverse-vowels-of-a-string

题目

编写一个函数,以字符串作为输入,反转该字符串中的元音字母。

示例 1:

输入: "hello"
输出: "holle"
示例 2:

输入: "leetcode"
输出: "leotcede"
说明:
元音字母不包含字母"y"。

思路

也是双指针,不过要注意大小写都可以,所以额外增加了一个判断函数判断是否需要反转,别的和344题基本相同。

代码

  public static boolean find(char c) {
    return !(c == 'a' || c == 'o' || c == 'e' || c == 'i' || c == 'u' || c == 'A' || c == 'O'
        || c == 'E' || c == 'I' || c == 'U');
  }

  public static String reverseVowels(String s) {
    char[] arr = s.toCharArray();
    int left = 0, right = arr.length - 1;
    while (left < right) {
      while (left < arr.length && find(arr[left])) {
        left++;
      }
      while (right >= 0 && find(arr[right])) {
        right--;
      }
      if (left >= right) {
        break;
      }
      char temp = arr[right];
      arr[right--] = arr[left];
      arr[left++] = temp;
    }
    String result = new String(arr);
    return result;
  }
原文地址:https://www.cnblogs.com/blogxjc/p/12316655.html