Question
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = “leetcode”,
dict = [“leet”, “code”].
Return true because “leetcode” can be segmented as “leet code”.
Show Tags
Show Similar Problems
Solution
Analysis
Get idea from Code Ganker”s 优快云
if using recursive function, the one substring will be calculated many times. That’s why we use dynamic programming. flag[i] records whether substring[0:i+i] is satisfied.
Code
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: Set[str]
:rtype: bool
"""
if s=='':
return True
flag = [False]*(len(s)+1)
flag[0] = True
for ind in range(len(s)):
newstr = s[:ind+1]
for inind in range(len(newstr)):
if flag[inind] and newstr[inind:] in wordDict:
flag[ind+1] = True
break
return flag[len(s)]