如何使用 Python 的 `str` 类型实现一个高效的字符串压缩算法?请给出代码示例并分析时间复杂度。

以下是一种基于 Python 的 str 类型实现的字符串压缩算法,它将连续重复的字符替换为字符及其出现次数,例如将字符串 "aaabbbcc" 压缩为 "a3b3c2"。这种算法的时间复杂度为 O(n),其中 n 是输入字符串的长度。

def compress_string(s: str) -> str:
    if not s:
        return ""
    
    compressed = []
    current_char = s[0]
    count = 1
    
    for char in s[1:]:
        if char == current_char:
            count += 1
        else:
            compressed.append(f"{current_char}{count}")
            current_char = char
            count = 1
    
    # 添加最后一个字符及其计数
    compressed.append(f"{current_char}{count}")
    
    compressed_str = "".join(compressed)
    return compressed_str if len(compressed_str) < len(s) else s

示例说明

  1. 输入: "aaabbbcc",输出: "a3b3c2"。
  2. 输入: "abc",输出: "abc"(因为压缩后长度没有减少)。
  3. 输入: "",输出: ""(空字符串处理)。

时间复杂度分析

  • 遍历字符串: 算法需要遍历字符串的所有字符一次,因此时间复杂度为 O(n)。
  • 辅助操作: 列表 compressed 的构建和字符串拼接操作的时间复杂度均为 O(n),但它们是线性叠加的,因此总时间复杂度仍为 O(n)。

空间复杂度分析

  • 辅助列表: 使用了一个列表 compressed 存储中间结果,其空间复杂度为 O(n)。在最坏情况下(例如字符串没有连续重复字符),列表的长度可能达到 2n(每个字符及其计数)。

优化点

  1. 提前终止: 如果压缩后的字符串长度不小于原始字符串长度,直接返回原字符串。
  2. 字符计数大于 9 的处理: 如果字符的连续出现次数超过 9,可以将计数拆分为多个部分,例如 a12 表示为 a12 而不是 a1a2。

改进后的代码示例

def compress_string_optimized(s: str) -> str:
    if not s:
        return ""
    
    compressed = []
    current_char = s[0]
    count = 1
    
    for char in s[1:]:
        if char == current_char:
            count += 1
        else:
            compressed.append(current_char + (str(count) if count > 1 else ""))
            current_char = char
            count = 1
    
    compressed.append(current_char + (str(count) if count > 1 else ""))
    
    compressed_str = "".join(compressed)
    return compressed_str if len(compressed_str) < len(s) else s

优化后的示例

  1. 输入: "aaabbbcc",输出: "a3b3c2"。
  2. 输入: "abc",输出: "abc"(不压缩)。
  3. 输入: "aabcccccaaa",输出: "a2bc5a3"(压缩部分字符)。

这种优化在不牺牲时间复杂度的情况下,进一步减少了压缩后的字符串长度。