Minimum Window Substring#127
Conversation
0aca7e3 to
16cc63f
Compare
| import math | ||
|
|
||
|
|
||
| class WindowInfo: |
There was a problem hiding this comment.
このクラスは必要でしょうか?
また、もしクラスにするなら、sizeはleft/rightが変わったときに自動計算するようにしないと、クラス自体が不変条件を満たすように自動的に振る舞ってくれないので、利用する側が不変条件を満たすこと(sizeがright-left+1になること)を注意しないといけないので、単に変数を羅列しているのと変わらないかなと思います。
There was a problem hiding this comment.
ご指摘の通りだと思います。updateメソッドを定義して更新をカプセル化しました(step3_revised.py)。
There was a problem hiding this comment.
そもそもsizeをメンバー変数として保存せず、その場で計算すると良いと思います。
class WindowInfo:
def __init__(self) -> None:
self.left: int | None = None
self.right: int | None = None
@property
def size(self) -> int | float:
if self.left is None or self.right is None:
return math.inf
return self.right - self.left + 1There was a problem hiding this comment.
C++ならstring_viewで良さそうですね。Pythonの標準ライブラリで相当するビューオブジェクトはないかもしれません。
class Solution {
public:
string minWindow(string s, string t) {
int cnt[128] = {};
for (char c : t) {
++cnt[c];
}
int unused = t.size();
string_view min_win;
int l = 0;
for (int r = 0; r < s.size(); ++r) {
if (--cnt[s[r]] >= 0) {
unused -= 1;
}
while (unused == 0) {
if (min_win.empty() || r - l + 1 < min_win.size()) {
min_win = string_view(s.begin() + l, s.begin() + r + 1);
}
if (++cnt[s[l++]] > 0) {
++unused;
}
}
}
return string(min_win);
}
};There was a problem hiding this comment.
たしかに@Propertyよりもメンバ変数の方が適切ですね。
C++のstring_viewはコピーをせずに覗き見ができるのですね。
https://cpprefjp.github.io/reference/string_view.html
|
|
||
|
|
||
| class WindowInfo: | ||
| left = None |
There was a problem hiding this comment.
クラスにするのであれば、left: Optional[int]とかにしたほうがいいかなと思います。なんでも入るべきではないでしょう。
|
|
||
| class Solution: | ||
| def minWindow(self, s: str, t: str) -> str: | ||
| required_count = collections.Counter(t) |
There was a problem hiding this comment.
required_countとwindow_countを両方使っていますが、一つにまとめて正負を反対にすると、すっきりするかなと思います。テクニックとしてはArai60の問題にもいくつか出てきますね。
ChatGPTによるサンプル:
import collections
import math
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = collections.Counter(t)
missing = len(t)
left = 0
best_left = 0
best_size = math.inf
for right, char in enumerate(s):
if need[char] > 0:
missing -= 1
need[char] -= 1
while missing == 0:
if right - left + 1 < best_size:
best_left = left
best_size = right - left + 1
left_char = s[left]
need[left_char] += 1
if need[left_char] > 0:
missing += 1
left += 1
return "" if math.isinf(best_size) else s[best_left : best_left + best_size]There was a problem hiding this comment.
hayashi-ay/leetcode#73
さんの 3rd が本質的に同様ですかね。
There was a problem hiding this comment.
二つの変数で管理する必要はないですね。最初の step1 で dict 二つで管理していたのに引きずられました。
https://leetcode.com/problems/minimum-window-substring/description/?envType=problem-list-v2&envId=rab78cw1