0345. Reverse Vowels of a String (E)

Posted mapoos

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了0345. Reverse Vowels of a String (E)相关的知识,希望对你有一定的参考价值。

Reverse Vowels of a String (E)

题目

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);
    }
}

以上是关于0345. Reverse Vowels of a String (E)的主要内容,如果未能解决你的问题,请参考以下文章

345. Reverse Vowels of a String

LeetCode Reverse Vowels of a String

LeetCode 345. Reverse Vowels of a String

LeetCode #345 Reverse Vowels of a String

[LeetCode]345 Reverse Vowels of a String

LeetCode 345. Reverse Vowels of a String