LeetCode 76. Minimum Window Substring - #67
Conversation
|
|
||
| 外側のループは右側 (substring の終わり) だけ動かしていけばスッキリ書けるのか、思い至らなかった。そこと、カウンタの上手い使い方を頭に入れれば、自分でも他の方々の step 3 に近いものが再現できそう。 | ||
|
|
||
| 軽くGoogleした限り、尺取り法という名前がどこから来たのかはよくわからなかった。 |
There was a problem hiding this comment.
あってるかわかりませんが、私は尺取り虫(が地面に設置する2点)っぽい動きから来てるのかなと思いました
There was a problem hiding this comment.
そのようですね、ありがとうございます!英語ではこのテクニックに名前がついていないよう (普通に sliding window?) なので、AtCoder界隈の方が名付けたのではないかと想像しますが、そのあたりはよくわかりませんね。
| import math | ||
|
|
||
|
|
||
| def include(c1: collections.Counter, c2: collections.Counter) -> bool: |
There was a problem hiding this comment.
Counterには比較演算子が Python3.10 以降あるので、それを使うと楽ができそうです
There was a problem hiding this comment.
c2 <= c1 でいけそうですね、ありがとうございます!
|
|
||
| start = 0 | ||
| min_start = -math.inf | ||
| min_end = math.inf |
There was a problem hiding this comment.
文字列のインデックスなら、0とlen(s)-1のほうが一般的かなと思います
There was a problem hiding this comment.
ありがとうございます。min_start と min_end はここでは条件を満たす最小のwindow の始まり・終わりという意味を持たせているので、個人的に min_start, min_end = 0, len(s) - 1で始めることに抵抗があったのですよね、条件を満たしていないので。
とはいえインデックスを math.inf で始めるのも型も合わず、また条件を満たしていない初期状態を明確に表せているかと言われたら微妙なのもわかります。
| class Solution: | ||
| def minWindow(self, s: str, t: str) -> str: | ||
| required = collections.Counter(t) | ||
| used = 0 |
| start = 0 | ||
| min_window_start = -math.inf | ||
| min_window_end = math.inf | ||
| for end in range(1, len(s) + 1): |
There was a problem hiding this comment.
0, len(s)(略して range(len(s)))という一般的な range ではいけないのでしょうか?
There was a problem hiding this comment.
ありがとうございます!これは単に私の好みで、始まりが inclusive で 終わりが exclusive だと都合が良いことが多いのでそうしているだけですね。例えば 29 行目でそのまま inclusive/exclusive のインデックスを渡せたりします。
end を inclusive にする方法も検討しましたが、インデックスが一つずれるだけで特に大きなメリット・デメリットが思いつかなかったので、自分がしっくりくる方にしました。
https://leetcode.com/problems/minimum-window-substring/description/