本文次要记录一下leetcode之反转字符串中的元音字母

题目

编写一个函数,以字符串作为输出,反转该字符串中的元音字母。 示例 1:输出:"hello"输入:"holle"示例 2:输出:"leetcode"输入:"leotcede" 提醒:元音字母不蕴含字母 "y" 。起源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/reverse-vowels-of-a-string著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。

题解

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);    }}

小结

这里先应用HashSet寄存大小写的元音字母,之后应用头尾指针同时对字符串数组进行遍历,当i指向的字符与j指向的字符都是元音时,进行替换同时更新指针,不是元音字符时仅仅更新指针。

doc

  • 反转字符串中的元音字母