Reverse All Words in a String 反转字符串中的所有单词
解法1
class Solution {
func reverseWords(_ s: String) -> String {
if s.count <= 1 {
return s
}
var result = ""
let array = s.split(separator: " ")
for characters in array {
result = result + characters.reversed() + " ";
}
result.removeLast()
return result;
}
}
解法2
class Solution {
func reverseWords(_ s: String) -> String {
if s.count <= 1 {
return s
}
let array = s.split(separator: " ")
let result = array.map { String($0.reversed()) }
return result.joined(separator: " ")
}
}
解法3
上面的两种方法都使用了
Swift
原生的反转方法reversed()
, 如果要求自己实现呢 ?
/// 反转一个指定的字符串
fileprivate func _reverse(_ chars: inout [Character], _ start: inout Int, _ end: inout Int) {
while start < end {
_swap(&chars, start, end);
start += 1
end -= 1
}
}
/// 交换字符数组中的两个字符元素
fileprivate func _swap(_ chars: inout [Character], _ p: Int, _ r: Int) {
(chars[p], chars[r]) = (chars[r], chars[p])
}