Leetcode Note: Go - Reverse Vowels of a String

Reverse Vowels of a String - LeetCode
https://leetcode.com/problems/reverse-vowels-of-a-string/

  • Go 言語で取り組んだメモ

所感

  • vowles (母音) を反転させる
    • a, i, u, e, o

回答

A golang solution - LeetCode Discuss
https://leetcode.com/problems/reverse-vowels-of-a-string/discuss/81415/A-golang-solution

func reverseVowels(s string) string {
    r := []byte(s)
    var index []int

    // index で母音を管理
    for i, v := range s {
        if v == 'a' || v == 'e' || v == 'i' || v == 'o' || v== 'u' ||
           v == 'A' || v == 'E' || v == 'I' || v == 'O' || v == 'U' {
            index = append(index, i)
        }
    }

    // 母音が 2 つ以上あれば反転を行う
    if len(index) >= 2 {
        i := 0
        j := len(index) - 1
        for i < j {
            r[index[i]], r[index[j]] = r[index[j]], r[index[i]]
            i++
            j--
        }
    }
    
    return string(r)
}