天天看點

LeetCode 345. Reverse Vowels of a String(翻轉元音字母)

原題網址:https://leetcode.com/problems/reverse-vowels-of-a-string/

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".

方法:使用兩個指針。

public class Solution {
    boolean[] vowel = { true, false, false, false, true, false, false, false, true, false, false, false, false, false,
        true, false, false, false, false, false, true, false, false, false, false, false };
    public String reverseVowels(String s) {
        if (s == null) return null;
        char[] sa = s.toCharArray();
        int i=0, j=sa.length-1;
        while (i<j) {
            while (i<j && (!Character.isLetter(sa[i]) || (Character.isLowerCase(sa[i]) && !vowel[sa[i]-'a']) || (Character.isUpperCase(sa[i]) && !vowel[sa[i]-'A']))) i++;
            while (i<j && (!Character.isLetter(sa[j]) || (Character.isLowerCase(sa[j]) && !vowel[sa[j]-'a']) || (Character.isUpperCase(sa[j]) && !vowel[sa[j]-'A']))) j--;
            if (i>=j) break;
            char c = sa[i];
            sa[i] = sa[j];
            sa[j] = c;
            i++;
            j--;
        }
        return new String(sa);
    }
}
           

另一種實作:

public class Solution {
    public String reverseVowels(String s) {
        char[] sa = s.toCharArray();
        int left = 0, right = sa.length-1;
        while (left < right) {
            while (left < right && !vowel(sa[left])) left ++;
            while (left < right && !vowel(sa[right])) right --;
            if (left < right) {
                char ch = sa[left];
                sa[left] = sa[right];
                sa[right] = ch;
                left ++;
                right --;
            }
        }
        return new String(sa);
    }
    private boolean vowel(char ch) {
        if (ch >= 'a') ch -= 'a'-'A';
        return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
    }
}