[Leetcode]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".

用動態規劃來做~dp[i]表示到字符串的第i個元素爲止能否用字典中的單詞表示~

class Solution:
    # @param s, a string
    # @param dict, a set of string
    # @return a boolean
    def wordBreak(self, s, dict):
        lenS = len(s)
        dp = [False for i in xrange(lenS + 1)]
        dp[0] = True
        for i in xrange(1, lenS + 1):
            for j in xrange(i - 1, -1, -1):
                if s[j:i] in dict and dp[j]:
                    dp[i] = True
                    continue
        return dp[lenS]


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章