# swift 算法 简单101.反转字符串II

    func reverseStr(_ s: String, _ k: Int) -> String {

var count = s.count
var index = 0
var str:String = ""
while count > 0 {

if count >= 2*k {
let begin = s.startIndex
let start = s.index(begin, offsetBy: index)
let end = s.index(begin, offsetBy: index+2*k)

let  sub4 = s[start..<end]

let begin1 = sub4.startIndex
let start1 = sub4.index(begin1, offsetBy: 0)
let end1 = sub4.index(begin1, offsetBy: k)
let  sub41 = s[start1..<end1]

let begin2 = sub4.startIndex
let start2 = sub4.index(begin2, offsetBy: k)
let end2 = sub4.index(begin2, offsetBy: 2*k)
let  sub42 = s[start2..<end2]
str += String(sub41.reversed()) + sub42
}else if count >= k && count < 2*k {
let begin = s.startIndex
let start = s.index(begin, offsetBy: index)
let end = s.index(begin, offsetBy:s.count)

let  sub4 = s[start..<end]

let begin1 = sub4.startIndex
let start1 = sub4.index(begin1, offsetBy: 0)
let end1 = sub4.index(begin1, offsetBy: k)
let  sub41 = s[start1..<end1]

let begin2 = sub4.startIndex
let start2 = sub4.index(begin2, offsetBy: k)
let end2 = sub4.index(begin2, offsetBy: sub4.count)
let  sub42 = s[start2..<end2]
str += String(sub41.reversed()) + sub42
break
}else if count < k {
let begin = s.startIndex
let start = s.index(begin, offsetBy: index)
let end = s.index(begin, offsetBy:s.count)

let  sub4 = s[start..<end]

str += String(sub4.reversed())
break
}
index += 2*k
count -= 2*k
}
return str
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客