最容易想到的方法,用空格分割字符串成一个数组,swift的这个方法 直接把分割出来有空格的去掉了
再根据数组逆序来组装字符串
func reverseWords(_ s: String) -> String {
let array = s.split(separator:" ")
let tempStr = array.reversed().joined(separator:" ")
return tempStr
}
另外的解法
func reverseWords(_ s: String) -> String {
let length = s.count
if length <= 0 {
return s
}
var array = Array(s)
//先要消除多余空格
//像是开头是空格的情况
var space = true
var cur = 0
for i in 0..<length {
if array[i] != " " {
array[cur] = array[i]
cur += 1
space = false
}else {
//第一次经历空格
if space == false {
space = true
array[cur] = " "
cur += 1
}
}
}
//有效长度
let len = space ? (cur - 1) : cur
if len <= 0 {
return ""
}
//去除多余部分
array.removeSubrange(len..<length)
reverseWord(&array, 0, len)
//开始逆序单词
//先寻找单词位置
var preIndex = -1
for i in 0..<len {
if array[i] == " "{
reverseWord(&array, preIndex + 1, i)
preIndex = i
}
}
//翻转最后一个单词
reverseWord(&array, preIndex + 1, len)
return String(array)
}
func reverseWord( _ array:inout Array<Character>,_ start:Int ,_ length:Int) {
var left = start ,right = length - 1
while left < right {
let temp = array[left]
array[left] = array[right]
array[right] = temp
left += 1
right -= 1
}
}
网友评论