码迷,mamicode.com
首页 > 其他好文 > 详细

0345. Reverse Vowels of a String (E)

时间:2020-06-28 09:27:54      阅读:41      评论:0      收藏:0      [点我收藏+]

标签:func   hello   evo   int   code   strong   pre   str   hat   

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)

标签:func   hello   evo   int   code   strong   pre   str   hat   

原文地址:https://www.cnblogs.com/mapoos/p/13200881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!