【Lintcode】1282. Reverse Vowels of a String

題目地址:

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

給定一個字符串,翻轉其中的元音字母(指aeiouAEIOUaeiouAEIOU)。對撞雙指針,代碼如下:

import java.util.Arrays;
import java.util.HashSet;
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
        if (s == null || s.isEmpty()) {
            return s;
        }
        
        char[] string = s.toCharArray();
        Set<Character> set = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
        int l = 0, r = string.length - 1;
        while (l < r) {
            while (l < r && !set.contains(string[l])) {
                l++;
            }
            while (l < r && !set.contains(string[r])) {
                r--;
            }
            swap(string, l++, r--);
        }
        
        return new String(string);
    }
    
    private void swap(char[] string, int i, int j) {
        char tmp = string[i];
        string[i] = string[j];
        string[j] = tmp;
    }
}

時間複雜度O(n)O(n),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章