/**
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
Subscribe to see which companies asked this question
*/
/*
Thinking:
这个比较简单,只需要一左一右交换,知道相遇就可以了
*/
func reverseString(_ s: String) -> String {
guard s.lengthOfBytes(using: .ascii) > 1 else {
return s
}
var array = s.characters.map { String($0) }
func swapArray(_ left: Int, _ right: Int) {
if (left != right) {
swap(&array[left], &array[right])
}
}
var left = 0
var right = array.count - 1
while left < right {
swapArray(left, right)
left += 1
right -= 1
}
return array.joined()
}
reverseString("a")
reverseString("ab")
reverseString("acddeasfaf")
网友评论