公式

B - データ圧縮 / Data Compression 解説 by admin

Qwen3-Coder-480B

Overview

Given a string consisting only of lowercase English letters, the task is to compress consecutive identical characters into the format “character + count”. However, if the count is 1, the number is omitted.

Approach

In this problem, we need to scan the string from the beginning and identify “consecutive runs of the same character.”
For example, with aaabbc:

  • The first a appears 3 times consecutively → a3
  • The next b appears 2 times consecutively → b2
  • The last c appears only once → c

A straightforward approach would be to check whether each character matches the next one while keeping a count.
However, naively counting one character at a time could become very inefficient in the worst case. To avoid TLE especially when the string is long, we want to process it in linear time.

For this problem, a technique called the two-pointer method (sliding window / caterpillar method) is effective.
We use two pointers, a left endpoint \(l\) and a right endpoint \(r\), to manage the current consecutive run.
We advance \(r\), and when we encounter a different character, we finalize the current run, append the result, and start the next run.

By doing this, we only need to scan the entire string once to efficiently obtain the compressed result.

Algorithm

  1. Read the string \(S\) as input.
  2. Prepare a list res to store the result.
  3. Initialize a variable l indicating the left endpoint (initially 0).
  4. Move a variable r indicating the right endpoint from 0 to \(|S|-1\) using a for loop.
  5. At each step, check the following condition:
    • r is at the last position of the string, OR
    • S[r] and S[r+1] are different characters
  6. If the above condition is satisfied:
    • Calculate the length of the current run [l, r] as cnt = r - l + 1.
    • If cnt is 1, append only the character to res; otherwise, append “character + count”.
    • Set l = r + 1 for the next run.
  7. Finally, concatenate res and output.

Example: Processing aaabbc

r S[r] Condition met cnt Appended content Update l
0 a ×
1 a ×
2 a 3 “a3” 3
3 b ×
4 b 2 “b2” 5
5 c 1 “c” 6

Final result: "a3b2c"

Complexity

  • Time complexity: \(O(|S|)\) — each character is referenced only once.
  • Space complexity: \(O(|S|)\) — the size of the list storing the compressed result is at most on the order of \(|S|\).

Implementation Notes

  • When determining the end of a run, do not forget to check r == len(S) - 1 (to avoid index errors).

  • Use "".join(res) for efficient string concatenation.

  • Be careful to omit the number when cnt == 1.

    Source Code

S = input()

res = []
l = 0
for r in range(len(S)):
    if r == len(S) - 1 or S[r] != S[r + 1]:
        cnt = r - l + 1
        res.append(S[l] + ("" if cnt == 1 else str(cnt)))
        l = r + 1

print("".join(res))

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

投稿日時:
最終更新: