B - データ圧縮 / Data Compression 解説 by admin
Qwen3-Coder-480BOverview
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
aappears 3 times consecutively →a3 - The next
bappears 2 times consecutively →b2 - The last
cappears 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
- Read the string \(S\) as input.
- Prepare a list
resto store the result. - Initialize a variable
lindicating the left endpoint (initially 0). - Move a variable
rindicating the right endpoint from 0 to \(|S|-1\) using a for loop. - At each step, check the following condition:
ris at the last position of the string, ORS[r]andS[r+1]are different characters
- If the above condition is satisfied:
- Calculate the length of the current run
[l, r]ascnt = r - l + 1. - If
cntis 1, append only the character tores; otherwise, append “character + count”. - Set
l = r + 1for the next run.
- Calculate the length of the current run
- Finally, concatenate
resand 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.
投稿日時:
最終更新: