/**
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".
*/
/**
Thinking:
A、E、I、O、U 都属于 vowels
给定两个游标,一个从左,一个从右,左边遇到元音停下来,
右边开始,右边遇到元音后进行交换,知道左右相遇
Swift 交换 string 内部字符太低效
转化为 Array 做交换更合适
*/
func reverseVowels(_ str: String) -> String {
guard str.unicodeScalars.count > 1 else {
return str
}
//是否匹配元音字母
func matchVowels(_ ch: String) -> Bool {
let chArray:[String] = ["A", "E", "I", "O", "U"]
let chLowCaseArray:[String] = ["a", "e", "i", "o", "u"]
if chArray.contains(ch) || chLowCaseArray.contains(ch) {
return true
}
return false
}
var reverseArray = str.characters.map { String($0) }
var left: Int = 0
var right: Int = str.characters.count - 1
//Swift string 内部元素交换,是否有更好的方法?
func swap(_ left: Int, _ right: Int) {
let temp = reverseArray[left]
print("\(reverseArray[left]), \(reverseArray[right])")
reverseArray[left] = reverseArray[right]
reverseArray[right] = temp
}
while left < right {
let ch = reverseArray[left]
//如果左边匹配,则进入到右边
if (matchVowels(ch)) {
while left < right {
let chRight = reverseArray[right]
//如果右边也匹配,则进入交换, 交换完毕,继续左边
if (matchVowels(chRight)) {
swap(left, right)
right -= 1
break
}
right -= 1
}
}
left += 1
}
return reverseArray.joined()
}
reverseVowels("hell again")
345. Reverse Vowels of a String
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Write a function that takes a string as input and reverse...
- 题目 Write a function that takes a string as input and reve...
- Write a function that takes a string as input and reverse...
- Write a function that takes a string as input and reverse...
- Write a function that takes a string as input and reverse...