345. Reverse Vowels of a String

Posted Machelsky

tags:

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

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

 思路:双指针首位夹逼,转成array来swap相对应的vowel,最后输出新的string

118/145

public class Solution {
    public String reverseVowels(String s) {
        ArrayList<Character> check=new ArrayList<Character>();
        check.add(‘a‘);
        check.add(‘e‘);
        check.add(‘i‘);
        check.add(‘o‘);
        check.add(‘u‘);
        check.add(‘A‘);
        check.add(‘E‘);
        check.add(‘I‘);
        check.add(‘O‘);
        check.add(‘U‘);
        
        char[] transfer=s.toCharArray();
        
        int i=0;
        int j=transfer.length-1;
        while(i<j)
        {
            if(!check.contains(transfer[i]))
            {
                i++;
                continue;
            }
            if(!check.contains(transfer[j]))
            {
                j--;
                continue;
            }
            char temp=transfer[i];
            transfer[i]=transfer[j];
            transfer[j]=temp;
            i++;
            j--;
        }
        return new String(transfer);
}
}

 

以上是关于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

345. Reverse Vowels of a Stringeasy

LeetCode 345. Reverse Vowels of a String

345. Reverse Vowels of a String