345. Reverse Vowels of a String

原题链接:https://leetcode.com/problems/reverse-vowels-of-a-string/description/
跟反转字符串那道题目类似,直接双指针方法走起:

import java.util.HashSet;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.reverseVowels("hello"));
        System.out.println(s.reverseVowels("leetcode"));
    }

    public String reverseVowels(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }

        HashSet<Character> set = new HashSet<>(10);
        set.add('a');
        set.add('o');
        set.add('e');
        set.add('i');
        set.add('u');
        set.add('A');
        set.add('O');
        set.add('E');
        set.add('I');
        set.add('U');

        char[] chars = s.toCharArray();
        int i = 0, j = s.length() - 1;
        while (i < j) {
            while (i < j && !set.contains(chars[i])) {
                i++;
            }
            while (j > i && !set.contains(chars[j])) {
                j--;
            }
            if (i == j) {
                return String.valueOf(chars);
            }
            chars[i] ^= chars[j];
            chars[j] ^= chars[i];
            chars[i] ^= chars[j];
            i++;
            j--;
        }
        return String.valueOf(chars);
    }

}
posted @ 2018-04-09 12:02  optor  阅读(117)  评论(0编辑  收藏  举报