diff --git a/139_word_break/problem.md b/139_word_break/problem.md new file mode 100644 index 0000000..97daf8a --- /dev/null +++ b/139_word_break/problem.md @@ -0,0 +1 @@ +## 問題: [139. Word Break](https://leetcode.com/problems/word-break/description/) diff --git a/139_word_break/step1.md b/139_word_break/step1.md new file mode 100644 index 0000000..de05b58 --- /dev/null +++ b/139_word_break/step1.md @@ -0,0 +1,24 @@ +# Step 1 + +- わからなかったので[NeetCodeの解説](https://www.youtube.com/watch?v=Sx9NNgInc3A)を見た + - 末尾から見て「ここから先を辞書の語で切れるか」を`boolean_list[i]`に記録するDP + - 空文字は `True`(`boolean_list[len(s)]`)。各位置 `i` で、辞書の語が `s` の先頭(`i` から)に合えば、その語の直後 `i+len(word)` が `True` なら `i` も `True`。最後に `boolean_list[0]` が答え。 + +```python +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + boolean_list = [False] * (len(s) + 1) + boolean_list[len(s)] = True + + for i in range(len(s) - 1, -1, -1): + for word in wordDict: + if i + len(word) <= len(s) and s[i:i + len(word)] in wordDict: + boolean_list[i] = boolean_list[i + len(word)] + if boolean_list[i]: + break + return boolean_list[0] +``` + +時間計算量: $O(nmt)$ + +空間計算量: $O(n)$ diff --git a/139_word_break/step2.md b/139_word_break/step2.md new file mode 100644 index 0000000..4b13370 --- /dev/null +++ b/139_word_break/step2.md @@ -0,0 +1,22 @@ +# Step 2 + +- DPテーブルの変数、良い名付け方が思いつかない + +```python +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + boolean_list = [False] * (len(s) + 1) + boolean_list[len(s)] = True + + for i in range(len(s) - 1, -1, -1): + for word in wordDict: + if i + len(word) <= len(s) and s[i:i + len(word)] in wordDict: + boolean_list[i] = boolean_list[i + len(word)] + if boolean_list[i]: + break + return boolean_list[0] +``` + +時間計算量: $O(nmt)$ + +空間計算量: $O(n)$ diff --git a/139_word_break/step3.md b/139_word_break/step3.md new file mode 100644 index 0000000..27b32a4 --- /dev/null +++ b/139_word_break/step3.md @@ -0,0 +1,22 @@ +# Step 3 + +```python +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + boolean_list = [False] * (len(s) + 1) + boolean_list[len(s)] = True + + for i in range(len(s) - 1, -1, -1): + for word in wordDict: + if i + len(word) <= len(s) and s[i:i + len(word)] in wordDict: + boolean_list[i] = boolean_list[i + len(word)] + if boolean_list[i]: + break + return boolean_list[0] +``` + +1回目: 2分 18秒 + +2回目: 2分 9秒 + +3回目: 1分 54秒