问题:
方法:
两个指针向中间移动,当左右指针相遇时停止,每个指针在遇到非字母时直接跳过,当左右指针都指向字母时交换,不断重复直到指针相遇。
class ReverseOnlyLetters {
fun reverseOnlyLetters(S: String): String {
val result = CharArray(S.length)
var start = 0
var end = S.lastIndex
while (start <= end) {
if (!S[start].isLetter()) {
result[start] = S[start]
start++
continue
}
if (!S[end].isLetter()) {
result[end] = S[end]
end--
continue
}
if (S[start].isLetter() && S[end].isLetter()) {
result[start] = S[end]
result[end] = S[start]
start++
end--
continue
}
}
return String(result)
}
}
fun main(args: Array<String>) {
val input = "-"
val reverseOnlyLetters = ReverseOnlyLetters()
print(reverseOnlyLetters.reverseOnlyLetters(input))
}
有问题随时沟通
网友评论