3. Longest Substring Without Repeating Characters#6
Conversation
| # @lc code=start | ||
| class Solution: | ||
| def lengthOfLongestSubstring(self, s: str) -> int: | ||
| char_index_map = dict() |
There was a problem hiding this comment.
char_index_map = {}
名前は、char_to_indexなどでもいいでしょう。
There was a problem hiding this comment.
コメントありがとうございます。char_to_index のほうがわかりやすそうですね、修正します。
初期化の方法ですが、{} はパッと見で dict か set かわかりにくいので、中身が空のときには明示的に dict() や set() と書くように意識していました。
There was a problem hiding this comment.
こんなコメントを頂いた事があります。
TORUS0818/leetcode#13 (comment)
| class Solution: | ||
| def lengthOfLongestSubstring(self, s: str) -> int: | ||
| char_index_map = dict() | ||
| start = -1 |
There was a problem hiding this comment.
このstartがexclusive(開区間)なのが、途中まで気づきませんでした。コメントなどで追記するか、inclusiveにすると分かりやすいかと思います。
There was a problem hiding this comment.
コメントありがとうございます。同じ文字が出てきた場合、過去に出てきたときの index が exclusive になるので合わせて start も exclusive にしていましたが、初見でコードを読む人に(コメントもなしで)それを汲み取らせるのはたしかに酷に思いました。start という変数名にそれ自身が含まれていないことにも違和感がありそう(読み手は inclusive に感じそう)です。
7c7303d で inclusive 版も提出してみました。
| start = 0 | ||
| longest_length = 0 | ||
| for i, char in enumerate(s): | ||
| if char in char_index_map: |
There was a problem hiding this comment.
コメントありがとうございます。start と char_index_map[char] + 1 の比較も if 文の and 条件に入れてしまうということですね。この問題を書いているときは max 一択でその他の選択肢をまったく考えていなかったので、他の選択肢もあるか考えるようにしてみます。
Approve ありがとうございます。 |
| start = 0 | ||
| longest_length = 0 | ||
| for i, char in enumerate(s): | ||
| if char in char_to_index: |
Problem
Description
O(N)、空間計算量:O(N)start = max(start, index_map[char])の部分をstart = index_map[char]としていたstart = 0と初期値を誤っていた(s = "a"のような1文字の場合に明らかに間違いだと気づける)index_map->char_index_maplength->longest_lengthNote