139. Word Break

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given s = "leetcode", dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

Solution: DP

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        can_break = [False] * (len(s) + 1)
        can_break[0] = True
        for idx in xrange(len(s)):
            if not can_break[idx]:
                continue
            for word in wordDict:
                high = idx + len(word)
                if high > len(s) or can_break[high]:
                    continue
                if s[idx: high] == word:
                    can_break[high] = True
        return can_break[-1]

results matching ""

    No results matching ""