Reverse Vowels of a String

weixin_34019929發表於2018-06-03

https://www.lintcode.com/problem/reverse-vowels-of-a-string/description

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

public class Solution {
    /**
     * @param s: a string
     * @return: reverse only the vowels of a string
     */
    public String reverseVowels(String s) {
        // write your code here
        LinkedList<Integer> list = new LinkedList<>();
        char[] chars = s.toCharArray();
        Set<Character> set = new HashSet<>();
        set.add('a');
        set.add('e');
        set.add('i');
        set.add('o');
        set.add('u');
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
            if (set.contains(Character.toLowerCase(aChar))) {
                list.add(i);
            }
        }
        while (list.size() > 1) {
            int left = list.removeFirst();
            int right = list.removeLast();
            char aChar = chars[left];
            chars[left] = chars[right];
            chars[right] = aChar;
        }
        return new String(chars);
    }
}

相關文章