139. Word Break

問(wèn)題描述

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

問(wèn)題分析

一開(kāi)始想wordDict建成樹(shù)狀來(lái)進(jìn)行搜索匹配,但是這么做超時(shí),主要原因是有很多分支導(dǎo)致很多并列的遞歸調(diào)用。
參考了九章算法,主要思路就是記錄可以到達(dá)的位置,然后從這種可以到達(dá)的位置再得到通過(guò)一個(gè)單詞可以到達(dá)的位置。

AC代碼

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: Set[str]
        :rtype: bool
        """
        n = len(s)
        if len(wordDict) == 0:
            return n == 0
        flag = [False for i in range(n+1)]
        flag[0] = True
        maxLen = max([len(word) for word in wordDict])

        for i in range(1, n+1):
            if not flag[i-1]:
                continue
            for j in range(1, min(n, i+maxLen) + 1):
                if s[i-1:j] in wordDict:
                    flag[j] = True
        return flag[n]

Runtime: 56 ms, which beats 70.62% of Python submissions.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容