例如
- 源字符串: “the sky is blue”
- 反转后字符串:“blue is sky the”
需要注意的点
- 每个单词长度不一样。
- 空格需要特殊处理。
分析
- 这道题目一看好简单,不就是反转字符串的翻版吗?是也不是
- 先将整个字符串翻转,“the sky is blue” -> “eulb si yks eht”
- 每个单词作为一个字符串单独翻转,“eulb si yks eht” -> “blue is sky the”
代码
//字符串翻转
fileprivate func charReverse<T>(_ chars: inout [T], _ start: Int, _ end: Int) {
var s = start, e = end
while s < e {
swap(&s, &e)
s += 1
e -= 1
}
}
//单词顺序进行反转
func wordReverse(s: String?) -> String? {
guard let s = s else {
return nil
}
var chars = Array(s), start = 0
charReverse(&chars, 0, chars.count - 1)
for i in 0..<chars.count {
if i == chars.count - 1 || chars[i + 1] == " " {
charReverse(&chars, start, i)
start = i + 2
}
}
return String(chars)
}
总结
时间复杂度 O(n)。