[leetcode] 139. Word Break

Description

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.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.

Example 1:

Input:

s = "leetcode", wordDict = ["leet", "code"]

Output:

true

Explanation:

Return true because "leetcode" can be segmented as "leet code".

Example 2:

Input:

s = "applepenapple", wordDict = ["apple", "pen"]

Output:

true

Explanation:

Return true because "applepenapple" can be segmented as "apple pen 
apple". Note that you are allowed to reuse a dictionary word.

Example 3:

Input:

 s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]

Output:

false

分析

题目的意思是:判断一个字符串能否分割成若干个字典中的单词。

  • dp[i] 表示源串的前i个字符可以满足分割,那么 dp[ j ] 满足分割的条件是存在k 使得 dp [k] && substr[k,j]在字典里。

C++

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        vector<bool> dp(s.size()+1,false);
        dp[0]=true;
        for(int i=0;i<s.length();i++){
            for(int j=i;j<s.length()&&dp[i];j++){
                if(find(wordDict.begin(),wordDict.end(),s.substr(i,j-i+1))!=wordDict.end()){
                    dp[j+1]=true;
                }
            }
        }
        return dp[s.length()];
    }
};

Python

假设我们有一个字符串s = “leetcode”,和一个字典wordDict = “leet”, “code”]。我们想知道字符串s能否被拆分成字典中的单词。

我们创建一个布尔型数组dp,长度为len(s) + 1,即9。dp[i]表示字符串s的前i个字符能否被拆分成字典中的单词。

初始化dp[0] = true,表示空字符串可以被拆分(因为没有任何单词)。

然后我们开始遍历字符串s的所有子字符串。对于每个子字符串,我们尝试所有可能的拆分位置。

例如,当i = 4时,我们考虑字符串s的前4个字符,即"leet"。我们尝试所有可能的拆分位置:

当j = 0时,我们检查dp[0](true)和"leet"是否在字典中(是)。所以,dp[4] = true,表示"leet"可以被拆分成字典中的单词。

当j = 1、2、3时,我们发现dp[j]都是false,所以不需要检查剩下的子字符串。

然后,当i = 8时,我们考虑字符串s的前8个字符,即"leetcode"。我们尝试所有可能的拆分位置:

当j = 0、1、2、3时,我们发现dp[j]都是false,所以不需要检查剩下的子字符串。

当j = 4时,我们检查dp[4](true)和"code"是否在字典中(是)。所以,dp[8] = true,表示"leetcode"可以被拆分成字典中的单词。

最后,我们返回dp[-1],即dp[8],它表示整个字符串s能否被拆分。在这个例子中,dp[8] = true,所以"leetcode"可以被拆分成"leet"和"code"。

在这个例子中,我们拆分了两次,但是实际上,dp[i]表示的是字符串s的前i个字符能否被拆分,而不是拆分的次数。拆分的次数取决于具体的字符串和字典。

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        # if word[j:i] in wordDict and dp[j] is True, dp[i]=True
        n = len(s)
        dp = [False]*(n+1)
        dp[0]=True
        for i in range(n+1):
            for j in range(i):
                if dp[j] and s[j:i] in wordDict:
                    dp[i]=True
        return dp[n]

参考文献

[编程题]word-break
[Leetcode] Word Break、Word BreakII

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值