每日一题.345. 反转字符串中的元音字母

解题思路

双指针

代码

class Solution {
    char[] chars;
    public String reverseVowels(String s) {
        chars = s.toCharArray();
        Set<Character> set = new HashSet<>();
        set.add('a');
        set.add('e');
        set.add('i');
        set.add('o');
        set.add('u');
        set.add('A');
        set.add('E');
        set.add('I');
        set.add('O');
        set.add('U');
        int low = 0,high = s.length()-1;
        while (low<high){
            while (low<s.length()-1 && !set.contains(chars[low])){
                low++;
            }
            while (high>=0 && !set.contains(chars[high])){
                high--;
            }
            if (low<high){
                // System.out.println(low);
                // System.out.println(high);
                swap(low,high);
                low++;
                high--;
            }
        }
        return new String(chars);
    }
    public void swap(int low,int high){
        char tem = chars[low];
        chars[low]=chars[high];
        chars[high]=tem;
    }
}
上一篇:力扣刷题笔记 剑指Offer 05


下一篇:每日一题.551. 学生出勤记录 I