[LeetCode By Go 87]345. 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”.

Note:
The vowels does not include the letter “y”.

解题思路

  1. 从两端遍历字符串,分别找到一个元音字母s[i], s[j],i < j, 然后交换两个字符;
  2. i, j = i+1, j-1 ;继续执行同样的操作,直至遍历完字符串

代码

func isVowels(r rune) bool {
    if r == rune('a') || r == rune('e') || r == rune('i') || r == rune('o') || r == rune('u') || r == rune('A') || r == rune('E') || r == rune('I') || r == rune('O') || r == rune('U'){
        return true
    }
    return false
}

func reverseVowels(s string) string {
    len1 := len(s)
    runeS := []rune(s)
    for i, j := 0, len1-1; i < j; i, j = i+1, j-1{
        for ;!isVowels(runeS[i]) && i < len1-1; i++ {}
        fmt.Printf("i:%+v\n", i)
        for ;!isVowels(runeS[j]) && j > 0; j-- {}

        if i < j {
            runeS[i], runeS[j] = runeS[j], runeS[i]
        }
    }

    ret := string(runeS)

    fmt.Printf("ret:%+v\n", ret)
    return ret
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/dd99a1b417c0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞