Leetcode: Word Break

来源:互联网 发布:淘宝店铺等级加分规则 编辑:程序博客网 时间:2024/05/16 08:00

Question

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”.

Show Tags
Show Similar Problems


Solution

Analysis

Get idea from Code Ganker”s CSDN

if using recursive function, the one substring will be calculated many times. That’s why we use dynamic programming. flag[i] records whether substring[0:i+i] is satisfied.

Code

class Solution(object):    def wordBreak(self, s, wordDict):        """        :type s: str        :type wordDict: Set[str]        :rtype: bool        """        if s=='':            return True         flag = [False]*(len(s)+1)        flag[0] = True        for ind in range(len(s)):            newstr = s[:ind+1]            for inind in range(len(newstr)):                if flag[inind] and newstr[inind:] in wordDict:                    flag[ind+1] = True                    break        return flag[len(s)]
0 0
原创粉丝点击