公式

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

Qwen3-Coder-480B

Overview

Given a string, compress characters that appear \(K\) or more times consecutively into the format “character + count”, and output all other characters as-is.

Analysis

In this problem, we need to scan the string from left to right while counting “how many times the same character appears consecutively.” For example, given the string aaabbc with \(K=2\):

  • The first a appears 3 times consecutively → compress to a3
  • The next b appears 2 times consecutively → compress to b2
  • The last c appears only 1 time → leave as c without compression

The key point is to split the string into “intervals of consecutive identical characters” and process each one.

A naive approach of using a nested loop to check the consecutive count for each character would result in a worst-case time complexity of \(O(|S|^2)\), which is too slow given the constraint \(|S| \leq 2 \times 10^5\).

Instead, we consider scanning the string once from the beginning, efficiently finding the start and end of each consecutive interval. This can be achieved by advancing the index until a different character appears. This allows us to process the entire string in \(O(|S|)\).

Algorithm

  1. Scan the string \(S\) from the beginning.
  2. For each character, count how many times it appears consecutively.
  3. If the consecutive count is \(K\) or more, append “character + count” to the result.
  4. Otherwise, append the character repeated by its consecutive count directly to the result.
  5. Process everything in a single pass to efficiently obtain the answer.

For example, with aaabbc and \(K=2\): - a appears 3 times → a3 - b appears 2 times → b2 - c appears 1 time → c

Result: a3b2c

Complexity

  • Time complexity: \(O(|S|)\)
  • Space complexity: \(O(|S|)\)

(The list result used to store the output string requires at most \(O(|S|)\) space.)

Implementation Notes

  • Use two pointers (i and j) to efficiently find intervals of consecutive identical characters.
  • Determine whether to compress based on the length of each interval.
  • Store results in a list first, then concatenate with ''.join() at the end for efficient string construction.
## Source Code

```python
import sys

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

    result = []
    i = 0
    n = len(S)

    while i < n:
        current_char = S[i]
        count = 0
        j = i
        while j < n and S[j] == current_char:
            count += 1
            j += 1

        if count >= K:
            result.append(current_char + str(count))
        else:
            result.append(current_char * count)
        
        i = j

    print(''.join(result))

if __name__ == "__main__":
    main()

This editorial was generated by qwen3-coder-480b.

投稿日時:
最終更新: