5.字符串压缩-力扣

283 阅读1分钟

题目
字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。

func compressString(_ S: String) -> String {
    if S.isEmpty {
        return ""
    }
    var times: Int = 0
    var newString: String = ""
    var record = S.first!
    for value in S {
        if record == value {
            times += 1
        }else{
            newString.append("\(record)\(times)")
            times = 1
            record = value
        }
    }
    newString.append("\(record)\(times)")

    print(S.count <= newString.count ? S: newString)
    return S.count <= newString.count ? S: newString
}

总结

  • 这道题,我认为题解在于怎么去计算每个字符的数量。
  • 我最开始想到的是通过set的数据结构来做,发现一个问题,题目允许重复字符的出现,所以pass
  • 然后想到的就是通过替换和加1的方式来解决