Medium

题目描述

给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s

**注意:**不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。

示例 1:

输入: s = "leetcode", wordDict = ["leet","code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。

示例 2:

输入: s = "applepenapple", wordDict = ["apple","pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以由 "apple" "pen" "apple" 拼接成。
     注意,你可以重复使用字典中的单词。

示例 3:

输入: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
输出: false

提示:

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • swordDict[i] 仅由小写英文字母组成
  • wordDict 中的所有字符串 互不相同

解题思路

这是一道经典的动态规划题目,核心思想是判断字符串能否被字典中的单词完美分割。

主要解法思路:

  1. 动态规划解法:使用 dp[i] 表示字符串前 i 个字符是否可以被字典中的单词拼接。状态转移方程为:如果 dp[j] 为真且 s[j:i] 在字典中,则 dp[i] 为真。

  2. 记忆化搜索:使用递归 + 备忘录的方式,从字符串起始位置开始尝试匹配字典中的每个单词。

  3. 字典树优化:构建 Trie 树来优化字典查找效率。

推荐解法:动态规划

为了提高查找效率,我们先将字典转换为哈希集合。然后使用一维 DP 数组,dp[i] 表示字符串前 i 个字符能否被完美分割。

初始状态:dp[0] = true(空字符串可以被分割)

状态转移:对于每个位置 i,遍历所有可能的分割点 j(0 <= j < i),如果 dp[j] 为真且子串 s[j:i] 在字典中,则 dp[i] = true

时间复杂度主要取决于字符串长度的平方,空间复杂度为线性。

代码实现

class Solution {
public:
    bool wordBreak(string s, vector<string>& wordDict) {
        unordered_set<string> dict(wordDict.begin(), wordDict.end());
        int n = s.length();
        vector<bool> dp(n + 1, false);
        dp[0] = true;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && dict.count(s.substr(j, i - j))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        
        return dp[n];
    }
};
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        word_set = set(wordDict)
        n = len(s)
        dp = [False] * (n + 1)
        dp[0] = True
        
        for i in range(1, n + 1):
            for j in range(i):
                if dp[j] and s[j:i] in word_set:
                    dp[i] = True
                    break
        
        return dp[n]
public class Solution {
    public bool WordBreak(string s, IList<string> wordDict) {
        HashSet<string> dict = new HashSet<string>(wordDict);
        int n = s.Length;
        bool[] dp = new bool[n + 1];
        dp[0] = true;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && dict.Contains(s.Substring(j, i - j))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        
        return dp[n];
    }
}
var wordBreak = function(s, wordDict) {
    const wordSet = new Set(wordDict);
    const n = s.length;
    const dp = new Array(n + 1).fill(false);
    dp[0] = true;
    
    for (let i = 1; i <= n; i++) {
        for (let j = 0; j < i; j++) {
            if (dp[j] && wordSet.has(s.substring(j, i))) {
                dp[i] = true;
                break;
            }
        }
    }
    
    return dp[n];
};

复杂度分析

复杂度类型复杂度说明
时间复杂度O(n²)其中 n 是字符串长度,需要双重循环遍历所有分割点
空间复杂度O(n + m)dp 数组需要 O(n) 空间,哈希集合需要 O(m) 空间,m 是字典大小

相关题目