139. Word Break -Medium

本文介绍了一个字符串分割问题及其解决方案。该问题要求判断一个非空字符串能否被分割成一个或多个字典中的单词序列。通过使用动态规划方法,文章详细解释了如何有效地解决这一问题,并给出了具体的Python实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

给出一个非空字符串s和一个包含一系列非空单词的字典wordDict,请你确定是否s可以用空格分割出一个或多个字典中的单词。字典中的单词不重复。

Example

*For example, given

s = “leetcode”,

dict = [“leet”, “code”].

Return true because “leetcode” can be segmented as “leet code”.

Solution

  • 动态规划解。定义dp[i]:s[:i]是否在字典中。那么递推式怎么找呢?假设我们要判断dp[i]是否在字典中,如果我们已知dp[j]在字典中(j < i),那么如果我们又判断得到s[j+1:i]也在字典中,那么我们就可以知道dp[i]在字典中了。即 dp[i] = dp[j] and s[j+1:i] in wordDict (j < i)

    class Solution(object):
        def wordBreak(self, s, wordDict):
            """
            :type s: str
            :type wordDict: List[str]
            :rtype: bool
            """
            dp = [True] + [False] * len(s)
            for index_s in range(1, len(s) + 1):
                for j in range(index_s):
                    # 如果前j个已经可以在字典中找到且j+1:index_s也在字典中(因为index的范围是1 -- len(s) + 1,所以写j:index_s)
                    if dp[j] and s[j:index_s] in wordDict:
                            # 代表前index_s个字符串可以在字典中找到(包括分解找到)
                            dp[index_s] = True
                            break
            return dp[-1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值