Leetcode - Reverse Vowels of a String

Question

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


Example

Given s = “hello”, return “holle”.
Given s = “leetcode”, return “leotcede”.


Java Code

public String reverseVowels(String s) {
    int len = s.length();
    if(len < 2) return s;
    char[] str = s.toCharArray();
    int i = 0;
    int j = len - 1;

    //從數組的兩端往中間搜索
    while(i < j) {
        if(isVowel(str[i])) {
            if(isVowel(str[j]))
                swap(str, i++, j--);//如果兩者都是元音字母,交換之且兩個指針都移向下一位
            else
                j--;//j指針一直遍歷直到指向元音字母
        }else
            i++;//i指針一直遍歷直到指向元音字母
    }

    return new String(str);
}

//判斷一個字符是否爲元音字母
public boolean isVowel(char ch) {
    switch(ch) {
        case 'a' :
        case 'e' :
        case 'i' :
        case 'o' :
        case 'u' :
        case 'A' :
        case 'E' :
        case 'I' :
        case 'O' :
        case 'U' :
            return true;
        default :
            return false;
    }
}

//交換數組中的兩個元素
public void swap(char[] str, int i, int j) {
    char temp = str[i];
    str[i] = str[j];
    str[j] = temp;
}

發佈了74 篇原創文章 · 獲贊 24 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章