当前位置:网站首页>The vowels in the inverted string of leetcode

The vowels in the inverted string of leetcode

2020-11-08 23:48:00 go4it

order

This article mainly records leetcode Reverse the vowels in a string

subject

 Write a function , String as input , Invert the vowels in the string .

 

 Example  1:

 Input :"hello"
 Output :"holle"
 Example  2:

 Input :"leetcode"
 Output :"leotcede"
 

 Tips :

 Vowels do not contain letters  "y" .

 source : Power button (LeetCode)
 link :https://leetcode-cn.com/problems/reverse-vowels-of-a-string
 Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Answer key

class Solution {
    Set<Character> set = new HashSet(){{
        add('a');
        add('e');
        add('i');
        add('o');
        add('u');
        add('A');
        add('E');
        add('I');
        add('O');
        add('U');
    }};

    public String reverseVowels(String s) {
        int i = 0;
        int j = s.length() - 1;
        char[] chars = s.toCharArray();
        while(i < j) {
            while (!set.contains(chars[i]) && i<j) {
                i++;
            }
            while (!set.contains(chars[j]) && i<j) {
                j--;
            }
            if (i < j) {
                char tmp = chars[i];
                chars[i] = chars[j];
                chars[j] = tmp;
                i++;
                j--;
            }
        }
        return new String(chars);
    }
}

Summary

So let's use this HashSet Storing vowels in uppercase and lowercase , After that, we use the head and tail pointer to traverse the string array at the same time , When i The characters pointed to and j When all the characters pointed to are vowels , Exchange and update the pointer at the same time , Only update the pointer when it is not a vowel character .

doc

版权声明
本文为[go4it]所创,转载请带上原文链接,感谢