題目
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".
解題思路
- 從兩端遍歷字符串,分別找到一個元音字母s[i], s[j],i < j, 然后交換兩個字符;
- 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
}