LeetCode 面试题 01.06. 字符串压缩

题目描述

面试题 01.06. 字符串压缩

思路分析

解法一:双指针计数(推荐)

核心思路

  • 用指针遍历字符串,统计连续相同字符的数量。
  • 每段压缩为 “字符 + 次数”,写入结果缓冲区。
  • 若压缩后长度不比原串短,直接返回原串。


复杂度分析

  • 时间复杂度:O(n),其中 n 为字符串长度。
  • 空间复杂度:O(n),结果缓冲区占用。
class Solution {
    public String compressString(String s) {
        if (s.length() == 0) {
            return s;
        }

        StringBuilder sb = new StringBuilder();
        int i = 0;

        // 双指针统计连续字符
        while (i < s.length()) {
            int j = i;
            while (j < s.length() && s.charAt(j) == s.charAt(i)) {
                j++;
            }
            sb.append(s.charAt(i)).append(j - i);
            i = j;
        }

        return sb.length() < s.length() ? sb.toString() : s;
    }
}
import "strconv"

func compressString(s string) string {
    if len(s) == 0 {
        return s
    }

    builder := make([]byte, 0, len(s))
    i := 0

    // 双指针统计连续字符
    for i < len(s) {
        j := i
        for j < len(s) && s[j] == s[i] {
            j++
        }
        builder = append(builder, s[i])
        builder = append(builder, []byte(strconv.Itoa(j-i))...)
        i = j
    }

    if len(builder) < len(s) {
        return string(builder)
    }
    return s
}

相似题目

题目 难度 考察点
443. 压缩字符串 中等 双指针
38. 外观数列 中等 字符串
316. 去除重复字母 中等
1047. 删除字符串中的所有相邻重复项 简单
271. 字符串的编码与解码 中等 字符串
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/35734145
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!