​LeetCode刷题实战345:反转字符串中的元音字母

程序IT圈

共 2719字,需浏览 6分钟

 · 2021-08-09

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 反转字符串中的元音字母,我们先来看题面:
https://leetcode-cn.com/problems/reverse-vowels-of-a-string/

Given a string s, reverse only all the vowels in the string and return it.


The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

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

示例


示例 1

输入:"hello"
输出:"holle"

示例 2

输入:"leetcode"
输出:"leotcede"


解题


这道题利用双指针,一个指头一个指向尾,遇到非元音字符就继续遍历,同时遇到元音字符就交换位置。注意循环内的判断顺序,先判断非元音字符会方便一些。

class Solution {
    public final static HashSet<Character> vowels = new HashSet<>(
        Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    );
    public String reverseVowels(String s) {
        if (s == null) return null;
        int i = 0;
        int j = s.length() - 1;
        char[] result = new char[s.length()];
        while (i <= j) {
            char ci = s.charAt(i);
            char cj = s.charAt(j);
            if (!vowels.contains(ci)) {
                result[i++] = ci;
            } else if (!vowels.contains(cj)) {
                result[j--] = cj;
            } else {
                result[i++] = cj;
                result[j--] = ci;
            }
        }
        return new String(result);
    }
}


好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:
LeetCode1-340题汇总,希望对你有点帮助!
LeetCode刷题实战341:扁平化嵌套列表迭代器
LeetCode刷题实战342:4的幂
LeetCode刷题实战343:整数拆分
LeetCode刷题实战344:反转字符串

浏览 7
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报