[LeetCode] Reverse Vowels of a String

457 查看

Problem

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

Note

第一种解法:将字符串转化为字符数组,用一头一尾两个指针向中间夹逼,遇到两个元音字母就进行位置交换。
第二种解法:相同的思路,一头一尾两个指针向中间夹逼。头指针是元音字母时,用尾指针找到最靠后的元音字母,并不断将靠后的元音字母加入StringBuilder;头指针是非元音字母时,就顺序放入非元音字母。
这样,只用头指针放非元音字母,只用尾指针放元音字母。
注意只有当头指针为元音字母时,才会操作尾指针。判断尾指针非元音字母的条件:
while (j >= 0 && "AEIOUaeiou".indexOf(s.charAt(j)) == -1) j--;

Solution

1. Two Pointers --6ms

public class Solution {
    static final String vowels = "aeiouAEIOU";
    public String reverseVowels(String s) {
        int first = 0, last = s.length() - 1;
        char[] array = s.toCharArray();
        while(first < last){
            while(first < last && vowels.indexOf(array[first]) == -1){
                first++;
            }
            while(first < last && vowels.indexOf(array[last]) == -1){
                last--;
            }
            char temp = array[first];
            array[first] = array[last];
            array[last] = temp;
            first++;
            last--;
        }
        return new String(array);
    }
}

2. StringBuilder --15ms

public class Solution {
    public String reverseVowels(String s) {
        StringBuilder sb = new StringBuilder();
        int j = s.length() - 1;
        for (int i = 0; i < s.length(); i++) {
            if ("AEIOUaeiou".indexOf(s.charAt(i)) != -1) {
                while (j >= 0 && "AEIOUaeiou".indexOf(s.charAt(j)) == -1) j--;
                sb.append(s.charAt(j));
                j--;
            }
            else sb.append(s.charAt(i));
        }
        return sb.toString();
    }
}