• 注册
• 查看作者
• Leetcode: 139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Note:

• The same word in the dictionary may be reused multiple times in the segmentation.

• You may assume the dictionary does not contain duplicate words.

Example 1:

`Input: s = "leetcode", wordDict = ["leet", "code"]Output: trueExplanation: Return true because "leetcode" can be segmented as "leet code".`

Example 2:

```Input: s = "applepenapple", wordDict = ["apple", "pen"]Output: trueExplanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.```

Example 3:

`Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]Output: false`

class Solution:

```    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
length = len(s)
res = [0] * (length+1)
res[0] = 1
for j in range(1,length+1):
for i in range(j):
if s[i:j] in wordDict and res[i]:
print(s[i:j])
res[j] = 1

return res[length]```

Dynamic Programing:

All the after-result depend on the previous calculation.

For example:

For res[j] to be True, res[i] and string s[i:j] in wordDict hace to be true.

Basic case is res[0] = 1 and goes through the string and the substring.

Time complexity is O(n^2) and space complexity is N

纽约州·法拉盛
• 0
• 1
• 0
• 1k
• 请登录之后再进行评论

• 0
管理员Lv. 44VIP小可爱
Nice
• 做任务
• 全部清空