[NeetCode 150] Word Break

Word Break

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of dictionary words.

You are allowed to reuse words in the dictionary an unlimited number of times. You may assume all dictionary words are unique.

Example 1:

复制代码
Input: s = "neetcode", wordDict = ["neet","code"]

Output: true

Explanation: Return true because "neetcode" can be split into "neet" and "code".

Example 2:

复制代码
Input: s = "applepenapple", wordDict = ["apple","pen","ape"]

Output: true

Explanation: Return true because "applepenapple" can be split into "apple", "pen" and "apple". Notice that we can reuse words and also not use all the words.

Example 3:

复制代码
Input: s = "catsincars", wordDict = ["cats","cat","sin","in","car"]

Output: false

Constraints:

复制代码
1 <= s.length <= 200
1 <= wordDict.length <= 100
1 <= wordDict[i].length <= 20

s and wordDict[i] consist of only lowercase English letters.

Solution

To break the string, we can break it step by step. If s 0 : n s_{0:n} s0:n can be broken into words, then we just need to consider whether there exists a position m m m that s n : m s_{n:m} sn:m is a word in dictionary. So, we can record the positions that the substrings before these positions are broken, and check whether we can find a substring after these position that appears in dictionary.

One plausible way is to enumerate the next position and check the substring between two positions, whose time complexity is O ( Len 2 ( s ) ) O(\text{Len}^2(s)) O(Len2(s)). Another way is to traverse the dictionary and find one can be put after the last position, whose time complexity is O ( Len ( s ) × ∑ w Len ( w ) ) O(\text{Len}(s)\times\sum_w\text{Len}(w)) O(Len(s)×∑wLen(w))

Code

Enumerate break position:

py 复制代码
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        word_set = set(wordDict)
        brk = [False]*(len(s)+1)
        brk[-1] = True
        for i in range(len(s)):
            subword = ''
            for j in range(i, -1, -1):
                subword = s[j]+subword
                if brk[j-1] and subword in word_set:
                    brk[i] = True
                    break
        print(brk)
        return brk[len(s)-1]

Enumerate dictionary words:

py 复制代码
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        dp = [False] * (len(s) + 1)
        dp[len(s)] = True

        for i in range(len(s) - 1, -1, -1):
            for w in wordDict:
                if (i + len(w)) <= len(s) and s[i : i + len(w)] == w:
                    dp[i] = dp[i + len(w)]
                if dp[i]:
                    break

        return dp[0]
相关推荐
一只鱼^_18 分钟前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼25 分钟前
Spring的 @Validate注解详细分析
前端·spring boot·算法
邹诗钰-电子信息工程28 分钟前
嵌入式自学第二十一天(5.14)
java·开发语言·算法
↣life♚1 小时前
从SAM看交互式分割与可提示分割的区别与联系:Interactive Segmentation & Promptable Segmentation
人工智能·深度学习·算法·sam·分割·交互式分割
zqh176736464691 小时前
2025年阿里云ACP人工智能高级工程师认证模拟试题(附答案解析)
人工智能·算法·阿里云·人工智能工程师·阿里云acp·阿里云认证·acp人工智能
fie88892 小时前
用模型预测控制算法实现对电机位置控制仿真
算法
Kent_J_Truman2 小时前
【交互 / 差分约束】
算法
ghie90902 小时前
x-IMU matlab zupt惯性室内定位算法
人工智能·算法·matlab
Magnum Lehar2 小时前
3d游戏引擎的Utilities模块实现
c++·算法·游戏引擎
yzx9910134 小时前
支持向量机的回归用法详解
算法·支持向量机·回归