LeetCode-Reverse Vowels of a String

Posted LiBlog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-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".

Note:
The vowels does not include the letter "y".

Solution:

public class Solution {
    public String reverseVowels(String s) {
        if (s.length()<=1) return s;
        
        HashSet<Character> vowels = new HashSet<Character>();
        vowels.add(‘a‘);
        vowels.add(‘e‘);
        vowels.add(‘i‘);
        vowels.add(‘o‘);
        vowels.add(‘u‘);
        vowels.add(‘A‘);
        vowels.add(‘E‘);
        vowels.add(‘I‘);
        vowels.add(‘O‘);
        vowels.add(‘U‘);
        
        char[] sArr = s.toCharArray();
        int p1 = 0, p2=s.length()-1;
        while (p1<p2){
            while (p1<p2 && !vowels.contains(sArr[p1])) p1++;
            while (p1<p2 && !vowels.contains(sArr[p2])) p2--;
            
            char temp = sArr[p1];
            sArr[p1++] = sArr[p2];
            sArr[p2--] = temp;
        }
        
        return new String(sArr);
    }
}

 

以上是关于LeetCode-Reverse Vowels of a String的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Reverse Bits

1119. Remove Vowels from a String - Easy

leetcode-Reverse Words in a String

LeetCode-Reverse Words in a String

[LeetCode 1371] Find the Longest Substring Containing Vowels in Even Counts

fromkeys方法的意外结果