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

给定一个字符串和一个整数 k,你需要对从字符串开头算起的每个 2k 个字符的前k个字符进行反转。如果剩余少于 k 个字符,则将剩余的所有全部反转。如果有小于 2k 但大于或等于 k 个字符,则反转前 k 个字符,并将剩余的字符保持原样。

示例:

输入: s = "abcdefg", k = 2
输出: "bacdfeg"
要求:

该字符串只包含小写的英文字母。
给定字符串的长度和 k 在[1, 10000]范围内。


解法:

    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
    }

 

发布了143 篇原创文章 · 获赞 54 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

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

分享到微信朋友圈

×

扫一扫,手机浏览