[LeetCode刷题日记(Day24)]:Word Break

Problem 139. Word Break

  • 题目描述
    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

    Input: s = "leetcode", wordDict = ["leet", "code"]
    Output: true
    Explanation: Return true because "leetcode" can be segmented as "leet code".
    
  • 解题思路
    本题大意是:给定字符串 s 和字符串集 wordDict ,判断 s 能否拆分成若干个子串,使得每一个子串都与 wordDict 中的一个元素匹配。可用动态规划来解决。算法思路如下:

  1. 令 s 的长度为 len,令 dp 为一个含 len+1 个元素的布尔数组,并初始化为 false。其中 dp[i] 表示 s 中前 i 个字符能够拆分成若干个子串,使得每一个子串都与 wordDict 中的一个元素匹配;
  2. 令 dp[0] = true;
  3. 对 dp 进行遍历,dp[i] = true 的条件是:存在 j<i,使得 dp[j] = true,并且 s 中从下标 j 到 i 组成的字符串在 wordDict 能够匹配;
  4. 最后返回 dp[len] 即可。
  • 代码实现
    该算法的 C++ 和 Python 代码如下:
class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        int len = s.length();
        vector<bool> dp(len+1, false);
        dp[0] = true;
        for(int i = 0; i <= len; ++i){
            for(int j = 0; j < i; ++j)
                if(dp[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end())
                    dp[i] = true;
        }
        return dp[len];
    }
};
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        size = len(s)
        dp = [False for i in range(size+1)]
        dp[0] = True
        for i in range(size+1):
            for j in range(i):
                if(dp[j] and s[j:i] in wordDict):
                    dp[i] = True
        return dp[size]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值