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".
python code:
class Solution:
# @param s, a string
# @param wordDict, a set<string>
# @return a boolean
def wordBreak(self, s, wordDict):
if not s or not wordDict: #邊界條件處理
return False
d=[0] #這個list用來記錄前多少個字符可以匹配到,如[0,2,4,6],表示前0,2,4,6個字符構成的子串可以成功匹配
for i in range(1,len(wordDict)+1): #檢驗s,從第一個字符到第一個字符直至第一個字符到最后一個字符的子串是否匹配
for j in range(len(d)-1,-1,-1): #s的前i個字符構成的子串怎樣才算匹配?上一個匹配的位置到i構成的子串加上前面某個能匹配的子串后可以
# 在wordDict中找到
if s[d[j]:i] in wordDict:
d.append(i)
break
return len(s)==d[-1] #如果長為len(s)的子串能匹配成功,那么return True
新聞熱點
疑難解答