345. Reverse Vowels of a String

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }

}

以上是关于345. Reverse Vowels of a String的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 345. Reverse Vowels of a String

LeetCode #345 Reverse Vowels of a String

[LeetCode]345 Reverse Vowels of a String

345. Reverse Vowels of a Stringeasy

LeetCode 345. Reverse Vowels of a String

345. Reverse Vowels of a String