LeetCode 140. Word Break II(Hard)

博客围绕LeetCode 140题Word Break II(困难)展开,题目是给定非空字符串和单词字典,在字符串中加空格构成句子,使每个单词都在字典中,需返回所有可能句子。最朴素解法是DFS但会超时,可利用LeetCode 139结果加速,时间复杂度为O(n2+m)。

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

查阅更多的题解,请点击

Problem

140. Word Break II(Hard)

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

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 = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]

Example 2:

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
Explanation: Note that you are allowed to reuse a dictionary word.

Example 3:

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

Solution

设s的长度为n,字典的大小为m

O ( n 2 + m ) O(n^2+m) O(n2+m) time

该问题最朴素的解法是DFS,显然该过程会超时,可以利用LeetCode 139的结果来加速该过程

class Solution
{
private:
    void getPath(const vector<bool> &dp, vector<string> &res, const unordered_set<string> &dicts, string &s, string cur, int start, int minLength, int maxLength)
    {
        int length = s.size();
        for (int pos = start + minLength; pos <= min(start + maxLength, length); ++pos)
        {
            if (dp[pos] && dicts.count(s.substr(start, pos - start)))
            {
                if (pos == length)
                    res.emplace_back(cur + s.substr(start, pos - start));
                else
                    getPath(dp, res, dicts, s, cur + s.substr(start, pos - start) + " ", pos, minLength, maxLength);
            }
        }
    }

public:
    vector<string> wordBreak(string s, vector<string> &wordDict)
    {
        unordered_set<string> dicts;
        vector<string> res;
        int minLength = INT_MAX, maxLength = 0;
        for (auto item : wordDict)
        {
            dicts.insert(item);
            minLength = min(minLength, (int)item.length());
            maxLength = max(maxLength, (int)item.length());
        }
        vector<bool> dp(s.size() + 1, false);
        dp[0] = true;
        for (int i = minLength; i <= s.size(); ++i)
        {
            for (int len = minLength; len <= min(maxLength, i); ++len)
            {
                if (dp[i - len] && dicts.count(s.substr(i - len, len)))
                    dp[i] = true;
            }
        }
        if (dp[s.size()])
        {
            getPath(dp, res, dicts, s, "", 0, minLength, maxLength);
        }
        return res;
    }
};

note:

  • 这里的最差情况不考虑unordered_set的最差,即认为insert和find都是O(1) time,不会出现hash碰撞

GitHub传送门

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值