Conversation
| expected[c] += 1 | ||
| actual = defaultdict(int) | ||
|
|
||
| def is_window_substring(): |
There was a problem hiding this comment.
工夫すると毎回全ての文字のカウントを確認しなくて済むような方法があります。
There was a problem hiding this comment.
class Solution {
public:
string minWindow(string s, string t) {
vector<int> counts(128);
for (char c : t) {
++counts[c];
}
int l = 0, num_used = 0, res_l = 0, res_len = 0;
for (int r = 0; r < s.size(); ++r) {
if (--counts[s[r]] >= 0) {
++num_used;
}
while (num_used == t.size()) {
if (int len = r - l + 1; res_len == 0 || len < res_len) {
res_l = l;
res_len = len;
}
if (++counts[s[l++]] > 0) {
--num_used;
}
}
}
return s.substr(res_l, res_len);
}
};There was a problem hiding this comment.
@liquo-rice
ありがとうございます。確かに毎回全部の文字をチェックしなくて良いですね。 c56a41f で書きました。
| minimum_range = (left, right) | ||
| char_to_freq[s[left]] -= 1 | ||
| left += 1 | ||
| if len(s) - left < len(t): |
There was a problem hiding this comment.
これはあんまり意味がない気がします。leftがインクリメントされるのは、is_window_substring() == trueの時のみですよね。
There was a problem hiding this comment.
たしかに、確認するにしてもwhile文の中の方が良さそうですね。入力ケースにもよりますが、基本的にはif文が増えることによって分岐予測ミスも含めた処理コストの増加の方が大きそうですね。
There was a problem hiding this comment.
len(s) - left < len(t)がTrueになるのは、sのlen(t)のsuffixがminimum window substringで、rightがすでにlen(s) - 1に到達したときだけではないでしょうか?
| left = 0 | ||
| for right in range(len(s)): | ||
| char_to_freq[s[right]] += 1 | ||
| while is_window_substring(): |
There was a problem hiding this comment.
この関数がchar_to_freqを受け取る作りの方が、while中で何をしたいかがぱっと見て分かると思いました。
There was a problem hiding this comment.
たしかにそうですね。関数シグネチャで引数がある方が意図がより明らかになりますね。
https://leetcode.com/problems/minimum-window-substring/