LeetCode 345. 反转字符串中的元音字母

题目:

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

  示例1:

输入: "hello"

输出: "holle"

  示例2:

输入: "leetcode"

输出: "leotcede"

思路:

  定义两个指针,左指针从左向右扫描找到元音字母,右指针从右向左扫描找到元音字母,扫描过程中判断左指针是否小于右指针,否则退出循环,直接交换(这时左右指针相等)。

代码:

  

class P345{
    public String reverseVowels(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }

        char[] arr = s.toCharArray();
        int left = 0;
        int right = arr.length - 1;
        char tmp;
     //外层循环
while (left < right) { while (left < right && !isVowels(arr[left])) { left++; } while (left < right && !isVowels(arr[right])) { right--; } tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; left++; right--; } return new String(arr); } private boolean isVowels(char ch) { return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'; } }
原文地址:https://www.cnblogs.com/xiaoxt/p/10657281.html