Conversation
nodchip
reviewed
Mar 17, 2024
| class Solution: | ||
| def lengthOfLongestSubstring(self, s: str) -> int: | ||
| left_index = 0 | ||
| char_to_last_appeared_index = {} |
There was a problem hiding this comment.
dict (CPython の実装は hash table) で持たせた場合、ハッシュ値の計算・余剰の計算・ランダムアクセスが行われます。このため、 list で持たせた場合と比べて、定数倍遅い場合があります。パフォーマンスがシビアな場合、実装して確かめたほうが良いかもしれません。ただ、パフォーマンスがシビアなコードは、より高速な言語で書いたほうが良いかもしれません。
Owner
Author
There was a problem hiding this comment.
なるほど, ありがとうございます.
sがunicodeのような文字列をもっている可能性を考えて, デメリットもなさそうだしdictを使おうとしたのですが, 同じO(1)でもdictの方がかなり複雑で遅そうですね.
| start_index = 0 | ||
| end_index = 0 | ||
| appeared_chars = set(s[0]) | ||
| while True: |
There was a problem hiding this comment.
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)
Owner
Author
|
ありがとうございます! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem link
見た問題, コメントについてはnote.mdに記載しております.