Skip to content

String Compression#131

Open
tom4649 wants to merge 2 commits into
mainfrom
443.String-Compression
Open

String Compression#131
tom4649 wants to merge 2 commits into
mainfrom
443.String-Compression

Conversation

@tom4649

@tom4649 tom4649 commented Jun 15, 2026

Copy link
Copy Markdown
Owner

chars[length] = chars[left]
length += 1
if right - left > 1:
for c in str(right - left):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

str(right - left) で、O(log chars.length) の文字数のメモリが確保されると思うのですが、それが constant extra space と言えるのかどうか気になりました。かりに str をしようしないとしたら、どのようなロジックにすればよいでしょうか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ご指摘の通りで、count の桁数分 O(log chars.length) の空間計算量になりますね。自力で気付けませんでした。以下の関数を定義することで constant extra space になるかと思います。

def append_count(length_before, count):
        length_after = length_before
        while count > 0:
            chars[length_after] = str(count % 10)
            count //= 10
            length_after += 1

        left = length_before
        right = length_after - 1
        while left < right:
            chars[left], chars[right] = chars[right], chars[left]
            left += 1
            right -= 1

        return length_after

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants