0345. Reverse Vowels of a String

0345. Reverse Vowels of a String #

题目 #

  • 给定字符串 s,反转其中的所有元素字母,并返回字符串。
  • 元音字母包含 'a''e''i''o''u' 及其大写形式。

思路 #

双指针 #

代码 #

双指针 (StringBuilder#

class Solution {
    boolean isVowel(Character ch) {
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true;
        if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') return true;
        return false;
    }
    public String reverseVowels(String s) {
        int i = 0, j = s.length() - 1;
        StringBuilder sb = new StringBuilder(s);
        while (i < j) {
            while (i < j && isVowel(s.charAt(i)) == false) i += 1;
            while (i < j && isVowel(s.charAt(j)) == false) j -= 1;
            Character ch = s.charAt(i);
            sb.replace(i, i + 1, String.valueOf(s.charAt(j)));
            sb.replace(j, j + 1, String.valueOf(ch));
            i += 1; j -= 1;
        }
        return sb.toString();
    }
}

双指针(String.toCharArray & String.valueOf#

class Solution {
    public void swap(char[] charArray, int i, int j) {
        char ch = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = ch;
    }
    public String reverseVowels(String s) {
        char[] vowels = new char[]{'a', 'e', 'i', 'o', 'u'};
        boolean[] isVowel = new boolean[128];
        for (char vowel: vowels) isVowel[vowel - ' '] = isVowel[Character.toUpperCase(vowel) - ' '] = true;
        
        char[] charArray = s.toCharArray();
        int i = 0, j = charArray.length - 1;
        while (i < j) {
            if (isVowel[charArray[i] - ' '] == true && isVowel[charArray[j] - ' '] == true) swap(charArray, i++, j--);
            else {
                if (isVowel[charArray[i] - ' '] == false) i += 1;
                if (isVowel[charArray[j] - ' '] == false) j -= 1;
            }
        }
        
        return String.valueOf(charArray);
    }
}