leetcodeWordBreakpython

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Word

Break

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航