公式

C - 文字列圧縮 / String Compression 解説 by admin 印刷ページ

GPT 5.2 High

Overview

Look at string \(S\) from left to right, count the length of each maximal run of consecutive identical characters, and if the run length is \(K\) or more, replace it with “character + count”; otherwise, output the original characters as-is.

Analysis

This compression can be processed independently for each “run” (a maximal consecutive sequence of the same character). In other words, there is no need to edit the entire string in a fine-grained manner — we just need to find each maximal interval of consecutive identical characters and look at its length.

For example, with aaabbc and \(K=2\), the consecutive runs are: - aaa (length 3) → \(3 \ge K\), so a3 - bb (length 2) → \(2 \ge K\), so b2 - c (length 1) → \(1 < K\), so c

Concatenating these in order gives a3b2c.

A naive implementation that “looks at one character at a time and appends to a string with +=” would cause copies on every concatenation in Python (since strings are immutable), resulting in worst-case \(O(|S|^2)\) time and potentially causing TLE. Instead, we append to a list and combine everything at the end with "".join(...), achieving \(O(|S|)\) overall.

Algorithm

  1. Start with position \(i = 0\).
  2. Let ch be the character \(S[i]\) for the current run, and advance position \(j\) starting from \(i+1\) as long as S[j] == ch.
    • The run is \(S[i:j]\), and the run length is cnt = j - i.
  3. If cnt >= K, append ch and cnt (as a string) to the result (e.g., a and 3 to form a3). Otherwise, append ch * cnt (e.g., a once gives a, twice gives aa).
  4. Move to the next unprocessed position by setting \(i = j\), and repeat until the end.
  5. Join all the accumulated parts and output.

In this method, each character is scanned at most once by \(j\), so the entire process runs in linear time.

Complexity

  • Time complexity: \(O(|S|)\)
  • Space complexity: \(O(|S|)\) (for the output array)

Implementation Notes

  • Do not build the output with string +=; instead, append to a list and join at the end (faster).

  • Using two pointers \(i, j\) to find the end of each consecutive run makes the implementation concise.

  • The problem states that “the maximum run length is 99,” so counts fit within 2 digits, but simply using str(cnt) handles the general case.

    Source Code

import sys

def main():
    S = sys.stdin.readline().strip()
    K = int(sys.stdin.readline().strip())

    res = []
    n = len(S)
    i = 0
    while i < n:
        ch = S[i]
        j = i + 1
        while j < n and S[j] == ch:
            j += 1
        cnt = j - i
        if cnt >= K:
            res.append(ch)
            res.append(str(cnt))
        else:
            res.append(ch * cnt)
        i = j

    sys.stdout.write("".join(res))

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.2-high.

投稿日時:
最終更新: