Algorithem_ReverseWords#
Reverse Words in a String III#
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Example 2:
Input: s = "God Ding"
Output: "doG gniD"
解法一#
逻辑:
把字符串根据空格切割成数组,然后遍历数组,对数组中字符串调用 reversed 方法,最后在使用空格 join 为字符串返回
代码如下:
class Solution {
func reverseWords(_ s: String) -> String {
let list = s.components(separatedBy: " ")
var results: [String] = []
for str in list {
let reverseStr = String(str.reversed())
results.append(reverseStr)
}
return results.joined(separator: " ")
}
}
虽然可以得出结果,但是和没用到 TwoPointers 算法,另一种解法是,使用 TwoPointers,先把字符串转为字符数组,然后遍历字符数组,如果当前字符为空格,则对空格前面(两个空格之间)的元素交换位置。
代码如下:
class Solution {
func reverseWords(_ s: String) -> String {
var characters = Array(s)
var start = 0
var end = 0
for i in 0..<characters.count {
let c = characters[i]
if String(c) == " " {
// 当前为空格,则 revese 前面的数据
end = i - 1
swapList(&characters, start, end)
start = i + 1
}
}
swapList(&characters, start, characters.count-1)
return String(characters)
}
func swapList(_ characters: inout [Character], _ start: Int, _ end: Int) {
var mutStart = start
var mutEnd = end
while mutStart < mutEnd {
characters.swapAt(mutStart, mutEnd)
mutStart += 1
mutEnd -= 1
}
}
}