前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:345. Reverse Vowels of a String

LeetCode笔记:345. Reverse Vowels of a String

作者头像
Cloudox
发布2021-11-23 15:33:12
2900
发布2021-11-23 15:33:12
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Note: The vowels does not include the letter "y".

大意:

写一个函数,输入一个字符串然后翻转里面的元音字母。 例1: 给出 s = "hello",返回"holle"。 例2: 给出 s = "leetcode",返回"leotcede"。 注意: 元音不包括字母“y”。

思路:

首先想到的一个思路是遍历字符串中每个字母,遇到元音字母就记录下字母和所在的位置。遍历完后,对着记录下来的元音字母,将字符串中的元音按照反序替换一遍就好了,这种做法也做出来了,但是结果非常耗时,花了200多ms。 后来想到了第二种方法,在字符串的头和尾都放一个指针进行遍历,两端向中间去遍历,当两端都遇到元音字母后,就对换。直到两个指针碰头为止。这个方法就快多了,同时优化一下检查是否是元音字母的方法,只需要几ms就搞定了。 需要注意的是题目中并没有说字符串是纯大写或者小写,所以大小写都要考虑,这个容易忽略。

代码1(Java):

代码语言:javascript
复制
public class Solution {
    public String reverseVowels(String s) {
        int[] vowelIndex = new int[s.length()];
        char[] vowelChar = new char[s.length()];
        int index = 0;// 标记上面两个数组记录的位置
        // 记录元音字母及出现的位置
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u' || s.charAt(i) == 'A' || s.charAt(i) == 'E' || s.charAt(i) == 'I' || s.charAt(i) == 'O' || s.charAt(i) == 'U') {
                vowelChar[index] = s.charAt(i);
                vowelIndex[index] = i;
                index++;
            }
        }
        // 替换元音字母位置
        if (index == 0) return s;
        else {
            StringBuffer buffer = new StringBuffer(s);
            for (int i = 0; i < index; i++) {
                buffer.replace(vowelIndex[i], vowelIndex[i]+1, String.valueOf(vowelChar[index-i-1]));
            }
            return buffer.toString();
        }
    }
}

代码2(Java):

代码语言:javascript
复制
public class Solution {
    static final String vowels = "aeiouAEIOU";
    public String reverseVowels(String s) {
        int first = 0, last = s.length() - 1;
        char[] array = s.toCharArray();
        while(first < last){
            // 正向找元音
            while(first < last && vowels.indexOf(array[first]) == -1){
                first++;
            }
            // 逆向找元音
            while(first < last && vowels.indexOf(array[last]) == -1){
                last--;
            }
            // 对换
            char temp = array[first];
            array[first] = array[last];
            array[last] = temp;
            first++;
            last--;
        }
        return new String(array);
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码1(Java):
  • 代码2(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档