亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

【leetcode80】Reverse Vowels of a String(元音字母倒敘)

题目描述:
写一个函数,实现输入一个字符串,然后把其中的元音字母倒叙
注意

元音字母包含大小写,元音字母有五个a,e,i,o,u

原文描述:

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".

思路:
  • 使用HashSet的数据结构存储者10个字符
  • 遍历字符串,使用int【s.length】记录元音的位置,元音的个数为n
  • 遍历字符串,根据上一个数组,把所有的元音字母(索引为i)换成string.charAt(n-i-1)处的字符
代码:
public class Solution {
    public String reverseVowels(String s) {
        if(s == null){
            return null;
        }
         int[] array = new int[s.length()];
        int index = 0;
        HashSet<Character> vowel = new HashSet<Character>();
        vowel.add('a');
        vowel.add('e');
        vowel.add('i');
        vowel.add('o');
        vowel.add('u');
        vowel.add('A');
        vowel.add('E');
        vowel.add('I');
        vowel.add('O');
        vowel.add('U');

        for (int i = 0; i < s.length(); i++) {
            if (vowel.contains(s.charAt(i))) {
                array[index] = i;
                index++;
            }
        }

        char[] result = new char[s.length()];
        result = s.toCharArray();
        for (int i = 0; i < index; i++) {
            result[array[i]] = s.charAt(array[index - i - 1]);
        }
        return String.valueOf(result);
    }
}

更多的leetcode的经典算法,查看我的leetcode专栏

點擊查看更多內容
3人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
移動開發工程師
手記
粉絲
424
獲贊與收藏
5663

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消