1们陆、翻轉(zhuǎn)字符串
Given s = "the sky is blue",
return "blue is sky the".
// 交換數(shù)組中兩個元素的位置
func swap<T>(_ chars: inout [T], _ p: Int, _ q: Int) {
(chars[p], chars[q]) = (chars[q], chars[p])
}
// 翻轉(zhuǎn)數(shù)組中指定范圍的元素
func reverse<T>(_ chars: inout [T], _ start: Int, _ end: Int) {
var start = start, end = end
// 這個循環(huán)里從兩頭開始交換元素直到start大于end說明替換完成
while start < end {
swap(&chars, start, end)
start += 1
end -= 1
}
}
func reverseWords(s: String?) -> String? {
guard let s = s else {
return nil
}
var chars = Array(s), start = 0
// 1、翻轉(zhuǎn)整個字符串
reverse(&chars, 0, chars.count - 1)
// 2叠必、每個單詞作為一個字符串單獨(dú)翻轉(zhuǎn)
for i in 0 ..< chars.count {
// 遍歷字符串,如果當(dāng)前位置的下一個字符是空格或者當(dāng)前字符是整個字符串的最后一個字符時可以認(rèn)為從start位置到當(dāng)前位置的字符串是一個單獨(dú)的單詞
if chars[i + 1] == " " || i == chars.count - 1 {
// 翻轉(zhuǎn)單獨(dú)的單詞
reverse(&chars, start, i)
start = i + 2
}
}
return String(chars)
}
let str = "the blue is sky"
print(reverseWords(s: str) ?? "")