Skip to content

3#3

Open
cheeseNA wants to merge 3 commits intomainfrom
3
Open

3#3
cheeseNA wants to merge 3 commits intomainfrom
3

Conversation

@cheeseNA
Copy link
Copy Markdown
Owner

Problem link
見た問題, コメントについてはnote.mdに記載しております.

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
left_index = 0
char_to_last_appeared_index = {}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

dict (CPython の実装は hash table) で持たせた場合、ハッシュ値の計算・余剰の計算・ランダムアクセスが行われます。このため、 list で持たせた場合と比べて、定数倍遅い場合があります。パフォーマンスがシビアな場合、実装して確かめたほうが良いかもしれません。ただ、パフォーマンスがシビアなコードは、より高速な言語で書いたほうが良いかもしれません。

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.

なるほど, ありがとうございます.
sがunicodeのような文字列をもっている可能性を考えて, デメリットもなさそうだしdictを使おうとしたのですが, 同じO(1)でもdictの方がかなり複雑で遅そうですね.

start_index = 0
end_index = 0
appeared_chars = set(s[0])
while True:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

end_index を 1 個ずつ動かして処理することで、よりシンプルなコードにできると思います。

...
start_index = 0
end_index = 0
counter = [0] * 256
while end_index < length:
    counter[s[end_index]] += 1
    while counter[s[end_index]] == 2:
        counter[s[start_index]] -= 1
    longest_length = max(longest_length, end_index - start_index + 1)

Copy link
Copy Markdown

@nodchip nodchip left a comment

Choose a reason for hiding this comment

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

よいと思います。

@cheeseNA
Copy link
Copy Markdown
Owner Author

ありがとうございます!

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