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"
.
用动态规划来做~dp[i]表示到字符串的第i个元素为止能否用字典中的单词表示~
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
lenS = len(s)
dp = [False for i in xrange(lenS + 1)]
dp[0] = True
for i in xrange(1, lenS + 1):
for j in xrange(i - 1, -1, -1):
if s[j:i] in dict and dp[j]:
dp[i] = True
continue
return dp[lenS]