C - 文字列圧縮 / String Compression 解説 by admin 印刷ページ
gemini-3-flash-previewOverview
Given a string \(S\), this problem asks you to compress the string by replacing any section where the same character appears \(K\) or more times consecutively with the format “(character)(count)”, while leaving all other parts unchanged.
Analysis
The key to solving this problem is how to efficiently find groups of consecutive identical characters (runs).
For example, given S = "aaabbc", K = 2, we need to split the string into the following groups:
- \(3\) occurrences of a
- \(2\) occurrences of b
- \(1\) occurrence of c
For each group, we determine whether its length (number of occurrences) is \(K\) or more:
- Group a: length \(3 \ge K\), so compress to a3.
- Group b: length \(2 \ge K\), so compress to b2.
- Group c: length \(1 < K\), so leave as c.
Concatenating these in order gives a3b2c.
Since the length \(|S|\) of the string is at most \(2 \times 10^5\), an \(O(|S|)\) algorithm that scans the string character by character to perform grouping is more than fast enough within the time limit.
Algorithm
We use the idea of run-length encoding. In Python, itertools.groupby allows us to express the grouping of consecutive elements very concisely.
- Scan the string \(S\) from the beginning and split it into groups of consecutive identical characters.
- For each group, perform the following:
- Obtain the character type
charand its consecutive countcount. - If
count >= k, append the stringchar + str(count)to the result list. - If
count < k, append the original stringchar * countto the result list.
- Obtain the character type
- Finally, join all strings in the result list and output the result.
Complexity
- Time Complexity: \(O(|S|)\)
- We scan the string once to form groups and perform a constant amount of work for each character, so the processing time is proportional to the length of the string.
- Space Complexity: \(O(|S|)\)
- Memory is needed to store the transformed string. In the worst case (e.g., when no compression is performed at all), it consumes roughly the same amount of memory as the original string.
Implementation Notes
Efficient string concatenation: In Python, directly concatenating strings in a loop with
result += stringcreates a new string object each time, which risks degrading the complexity to \(O(|S|^2)\). By keepingresultas a list and using"".join(result)at the end, we can safely concatenate in \(O(|S|)\).Using groupby:
itertools.groupbyis a convenient function that returns consecutive identical elements as an iterator. By using this, we avoid writing complex loops with manual index management, which helps prevent bugs.Source Code
import sys
from itertools import groupby
def main():
# 入力を標準入力からすべて読み込み、空白文字で分割します
input_data = sys.stdin.read().split()
if len(input_data) < 2:
return
s = input_data[0]
k = int(input_data[1])
result = []
# itertools.groupbyを使用して、連続する同じ文字をグループ化します
for char, group in groupby(s):
# 現在の文字の連続出現回数をカウントします
count = 0
for _ in group:
count += 1
# 連続回数がK回以上の場合は圧縮形式「(文字)(出現回数)」に変換
if count >= k:
result.append(char + str(count))
# K回未満の場合はそのままの文字列として追加
else:
result.append(char * count)
# すべてのパーツを結合して出力します
print("".join(result))
if __name__ == "__main__":
main()
This editorial was generated by gemini-3-flash-preview.
投稿日時:
最終更新: