您的位置:首页 > 其它

Leetcode: Word Break

2015-08-29 12:57 309 查看

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

[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)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: