C - 文字列圧縮 / String Compression Editorial by admin Editorial for printing
Qwen3-Coder-480BOverview
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
aappears 3 times consecutively → compress toa3 - The next
bappears 2 times consecutively → compress tob2 - The last
cappears only 1 time → leave ascwithout 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
- Scan the string \(S\) from the beginning.
- For each character, count how many times it appears consecutively.
- If the consecutive count is \(K\) or more, append “character + count” to the result.
- Otherwise, append the character repeated by its consecutive count directly to the result.
- 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 (
iandj) 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.
posted:
last update: