Create 139. Word Break.md#39
Conversation
| def break_word_if_match(word): | ||
| for target in wordDict: | ||
| if word.startswith(target): | ||
| breaked_word = word[len(target):] |
There was a problem hiding this comment.
breakedは不自然(正しくはbroken)なのと、この場合はrestとかでいい気がします。
|
|
||
| stack = [s] | ||
| while stack: | ||
| word = stack[-1] |
There was a problem hiding this comment.
wordと書くと何を指してるのかよく分からないので、currentとかでいいかもしれません。
他のものと合わせると、currentを関数に与えて得たsuffixが残るといった形になって僕にとっては読みやすくなる気がします。
| def wordBreak(self, s: str, wordDict: List[str]) -> bool: | ||
| checked = set() | ||
|
|
||
| def break_word_if_match(word): |
There was a problem hiding this comment.
break_word_if_matchだと何が戻ってくるのか分からないので、get_suffix_after_matchとかの方が良さそうです。
There was a problem hiding this comment.
レビューありがとうございます。
分かりやすいですね。いまremove_prefix_if_matchも思いつきました。
| def break_word_if_match(word): | ||
| for target in wordDict: | ||
| if word.startswith(target): | ||
| breaked_word = word[len(target):] |
There was a problem hiding this comment.
これ、結果的に全部コピーしていますが、インデックスだけ保存するのも手です。
startswith はオプションの start でどこからチェックするかを変えられますね。
There was a problem hiding this comment.
startswithを使えばコピーする必要がないんですね。気付かなかったです。
| if breaked_word == '': | ||
| return True | ||
| if breaked_word == word: | ||
| stack.pop() |
There was a problem hiding this comment.
このコードはわりと直感的でないところがあると思います。
マッチさせるものは "aaaaab" に対して、["aaa", "ab", "aa"] としましょう。
このコードは breaked_word("aaaaab") が2回呼ばれてしかも結果が変わりますね。"aab" と "aaab" です。
これ、結構驚きじゃないですか。
私だったら全候補を返します。
There was a problem hiding this comment.
確かに直感的ではないですね。
このソースはDFSっぽいイメージをもって書いたので一つ返しました。
There was a problem hiding this comment.
二分木のdfsも再帰を使うと思っている通りのdfsになりますが、スタックを使うとそうならないので、多少ジグザグする探索でもdfsとして受け入れられると思います。
| - Acceptされることを喜ばないほうが良い | ||
| - 書く能力よりも読む能力が足りていない。 | ||
| - 脳内のデバッガーを走らせる |
There was a problem hiding this comment.
- Acceptされることを喜ばないほうが良い
- 書く能力よりも読む能力が足りていない。
- 脳内のデバッガーを走らせる
いいこと言ってますね。
|
|
||
| def break_word_if_match(word): | ||
| for target in wordDict: | ||
| if word.startswith(target): |
There was a problem hiding this comment.
word: 文字列sの任意のi以降
target: wordListの単語の一つ
こう整理するとwordという変数名の対応関係が変になっていると思います。つまり、wordという変数名があったらwordListの単語の一つかなと思いたくなりますし、sのi以降の文字列に対して「単語」という意味のwordという変数名をつけるのも変だと思いました。
There was a problem hiding this comment.
文字列を変数名にするのが上手くできなくてそう書いてます。word→string_、target→wordとかが分かりやすいでしょうか。
There was a problem hiding this comment.
そうですね、私はword -> s_suffixみたいにするかなと思いました。
|
動的計画法ぽくやる方法もあります! みたいな感じです。 |
https://leetcode.com/problems/word-break/description/