我面对这个问题。当我试图通过使用双指针模式来逆转swift中的字母时,它实际上是在做交换。sample - Test 123字符串2指针输出- gnir 123 tStseT期望输出- tseT 123 gnirtS有人能建议一下方法吗,或者给出代码的例子?
func reverseOnlyLetters(_ S: String) -> String {
var a = Array(S.unicodeScalars)
var i = 0
var j = a.count - 1
while i < j {
while !CharacterSet.letters.contains(a[i]) && i < j { i += 1 }
while !CharacterSet.letters.contains(a[j]) && i < j { j -= 1 }
let t = a[i]
a[i] = a[j]
a[j] = t
i += 1
j -= 1
}
var ret = ""
a.forEach({ ret += String(Character(UnicodeScalar($0))) })
return ret
}
try this:
func reverseOnlyLetters(_ S: String) -> String {
let components = S.components(separatedBy: " ")
let reversedComponents = components.map { Int($0) == nil ? String($0.reversed()) : $0 }
return reversedComponents.joined(separator: " ")
}
如果仍然不正确,请给我更多的信息