LeetCode--Word Break(分词)Python

来源:互联网 发布:qq宠物 知乎 编辑:程序博客网 时间:2024/05/17 23:47

题目:

给定一个字符串s,和一个词典Dict。判断该字符串s是否可以完全拆分为Dict中的单词。

解题思路:

考虑使用递归的方法。用output来存储从0到当前位置的字符串是否可以完全拆分为Dict中的单词。判断当前字符串是否可以完全拆分的问题,可以化解为从之前所有可以完全拆分的位置到当前位置的字符串是否在给定词典中,若在,则当前位置可以完全拆分,否则不行。该方法需要用一个列表来存储当前字符串所有可以完全拆分的位置。

代码(Python):

class Solution(object):    def wordBreak(self, s, wordDict):        """        :type s: str        :type wordDict: List[str]        :rtype: bool        """        Dict = {}        for i in wordDict:            Dict[i]=1        n = len(s)        output = [0]*(n+1)        output[0] = 1                sure_index = [0]                for i in range(n):            for j in range(len(sure_index)):                if s[sure_index[j]:i+1] in Dict:                    output[i+1]=1                    sure_index.append(i+1)                    break                            if output[n]==1:            return True        else:            return False


原创粉丝点击