【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,可以改写成递归,但是我写不出来,待解

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/86238944
今日推荐