LeetCode-345. 反转字符串中的元音字母
给你一个字符串 s ,仅反转字符串中的所有元音字母,并返回结果字符串。
元音字母包括 ‘a’、‘e’、‘i’、‘o’、‘u’,且可能以大小写两种形式出现不止一次。
地址:https://leetcode.cn/problems/reverse-vowels-of-a-string/?envType=study-plan-v2&envId=leetcode-75
实现思路:构造一个栈用于保存字符串s中的元音字母,再遍历字符串若为元音字母则从栈中取元素,反之从原字符串中取元素。
// 辅助函数用于判断是否是元音字母
func isVowel(ch uint8) bool {if ch == 'A' || ch == 'a' || ch == 'E' || ch == 'e' || ch == 'I' || ch == 'i' || ch == 'O' || ch == 'o' || ch == 'U' || ch == 'u' {return true}return false
}
func reverseVowels(s string) string {res := ""stack := []uint8{}for i := 0; i < len(s); i++ {if isVowel(s[i]) {stack = append(stack, s[i])}}index := len(stack) - 1for i := 0; i < len(s); i++ {if isVowel(s[i]) {res += string(stack[index])index--continue}res += string(s[i])}return res
}