Reverse Vowels of a String(345)

Write a function that takes a string as input and reverse only the

vowels of a string.

Example 1: Given s = "hello", return "holle".

Example 2: Given s = "leetcode", return "leotcede".

思路: 使用two pointers, 一个指针从头到尾,另一个指针从尾到头,一旦发现原音字母就swap。 判断某些元素是否在集合中, 使用hashset。

时间复杂度: O(n) n is length of string
空间复杂度: O(n)

public class Solution {
    public String reverseVowels(String s) {
        Set<Character> set = new HashSet<Character>();
        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');
        char[] c = s.toCharArray();
    
        int i = 0, j = s.length() - 1;
        while (i < j) {
            while (i < j && !set.contains(c[i])) {
                i++;
            }
            while (i < j && !set.contains(c[j])) {
                j--;
            }
            char tmp = c[i];
            c[i] = c[j];
            c[j] = tmp;
            i++;
            j--;
        }
        return string.valueOf(c);
    }
}


colorfuladventure
4 声望4 粉丝

引用和评论

0 条评论