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: true
Explanation: Return true because
Example 2:
Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false
这是一道动态规划的题,可以先建立一个list,然后循环遍历。
比如example3中,建立数组[True, False, False, False, False, False, False, False, False, False]
第一次循环后,因为cat和cats都在wordDict中,所以数组变为[True, False, False, True, True, False, False, False, False, False]
第二次循环后,cat后面可以接sand,cats后面可以接and,所以数组变为
[True, False, False, True, True, False, False, True, False, False](两种方式都是以'd'为结尾,所以只有一个变为True)
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
dp = [False for i in range(len(s)+1)]
dp[0] = True
for i in range(1,len(s)+1):
for word in wordDict:
if word == s[i-1:i+len(word)-1] and dp[i-1]:
dp[i+len(word)-1]=True
return dp[-1]