1. 程式人生 > >【LeetCode 中等題】65-單詞拆分

【LeetCode 中等題】65-單詞拆分

題目描述:給定一個非空字串 s 和一個包含非空單詞列表的字典 wordDict,判定 s 是否可以被空格拆分為一個或多個在字典中出現的單詞。

說明:

  • 拆分時可以重複使用字典中的單詞。
  • 你可以假設字典中沒有重複的單詞。

示例 1:

輸入: s = "leetcode", wordDict = ["leet", "code"]
輸出: true
解釋: 返回 true 因為 "leetcode" 可以被拆分成 "leet code"。

示例 2:

輸入: s = "applepenapple", wordDict = ["apple", "pen"]
輸出:
true 解釋: 返回 true 因為 "applepenapple"可以被拆分成 "apple pen apple"。注意你可以重複使用字典中的單詞。

示例 3:

輸入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
輸出: false

解法1。BFS做法,遍歷s,找到第一個在worddic裡的單詞結尾下標,把下標放到佇列裡面,然後後面的子串迭代判斷,直到最後一個字元,遍歷完畢未返回True的情況就是沒找到,返回False。

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        if not s or not wordDict:
            return False
        q = [0]
        visited = [0]*len(s)
        wordSet = set(wordDict)
        while q:
            start = q.pop(0)
            if visited[start] == 0:
                for i in range(start+1, len(s)+1):
                    if s[start:i] in wordSet:
                        q.append(i)
                        if i == len(s):
                            return True
                visited[start] = 1
        return False

解法2。DP,用一個dp陣列記錄s中截至哪個下標的子串s[:i]是在字典裡可以找到的。

class Solution(object):
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        if not s or not wordDict:
            return False
        wordSet = set(wordDict)
        dp = [0]*(len(s)+1)
        dp[0] = 1
        for i in range(len(dp)):
            for j in range(i):
                if dp[j] == 1 and s[j:i] in wordSet:
                    dp[i] = 1    # dp記錄的是子串s[:i]是在字典裡,i是截至此的下標+1
                    break
        return dp[-1] == 1

解法3。有BFS就有DFS,可以改寫成遞迴,但是我寫不出來,待解