给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。
给出
s = “lintcode”
dict = [“lint”,”code”]
返回 true 因为”lintcode”可以被空格切分成”lint code”
动态规划。
第一种:
dp[i]表示前i个字符能否被切分。前i个字符能否被切分依赖于下面所述:
如果前i-1个字符能被切分,而且第i个字符在dict中,则dp[i]=1.
如果前i-2个字符能被切分,而且第i-1到第i个在dict中,则dp[i]=1
如果前i-3个字符能被切分,而且第i-2到第i个在dict中,则dp[i]=1
……
如果前0个字符能被切分,而且第1到第i个在dict中,则dp[i]=1
代码如下:
class Solution:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
# write your code here
n=len(s)
if len(dict)==0 and len(s)!=0:
return False
dp=[0 for x in range(n+1)]
dp[0]=1
for i in range(1,n+1):
for j in range(1,i+1):
if dp[i-j]==1 and s[i-j:i] in dict:
dp[i]=1
break
if dp[n]==1:
return True
else:
return False
这样会超时。。。
第二种:
来看代码
class Solution:
# @param s: A string s
# @param dict: A dictionary of words dict
def wordBreak(self, s, dict):
# write your code here
n=len(s)
if len(dict)==0 and len(s)!=0:
return False
dp=[0]*(n+1)
dp[0]=1
for i in range(0,n+1):
if (not dp[i]): #如果dp[i]=0,则继续找到dp[i]=1的位置
continue
for word in dict: #依次判断字典中的每个单词
length=len(word)
end=i+length
if end>n: #如果第i位置加上字典中该词的长度超过了整个字符串s的长度,肯定不能以该单词来切分
continue
if s[i:end]==word:#没超过长度的话,判断i位置向后长度为length的片段和该单词是否匹配
dp[end]=1
#注意此处不能加break,要判断每个单词,这样才可以更新所有可以切分的位置
if dp[n]==1:
return True
else:
return False
第二种方法学习于下面
你看看别人家的孩子%>_<%