题目
给你一个字符串 s 和一个字符串列表 wordDict 作为字典。如果可以利用字典中出现的一个或多个单词拼接出 s 则返回 true。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例 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
题解
classSolution{publicbooleanwordBreak(Strings,List<String>wordDict){intmaxLen=0;for(Stringword:wordDict){maxLen=Math.max(maxLen,word.length());}Set<String>words=newHashSet<>(wordDict);intn=s.length();boolean[]f=newboolean[n+1];f[0]=true;for(inti=1;i<=n;i++){for(intj=i-1;j>=Math.max(i-maxLen,0);j--){if(f[j]&&words.contains(s.substring(j,i))){f[i]=true;break;}}}returnf[n];}}解析
出自:教你一步步思考 DP:从记忆化搜索到递推,附题单!(Python/Java/C++/Go/JS/Rust)
classSolution{publicbooleanwordBreak(Strings,List<String>wordDict){// 初始化字典中最长单词的长度为0intmaxLen=0;// 遍历字典,找出最长单词的长度for(Stringword:wordDict){maxLen=Math.max(maxLen,word.length());}// 将字典转为HashSet,提升查找效率(O(1)平均时间)Set<String>words=newHashSet<>(wordDict);// 获取输入字符串s的长度intn=s.length();// 创建动态规划数组f,f[i]表示s的前i个字符能否被拆分为字典中的单词boolean[]f=newboolean[n+1];// 空字符串视为可拆分,作为DP起点f[0]=true;// 从1到n遍历每个位置i,计算f[i]for(inti=1;i<=n;i++){// 从i-1向前遍历j,但最多只回溯maxLen个字符(剪枝优化)for(intj=i-1;j>=Math.max(i-maxLen,0);j--){// 如果前j个字符可拆分(f[j]为true),且子串s[j:i]在字典中if(f[j]&&words.contains(s.substring(j,i))){// 则前i个字符也可拆分f[i]=true;// 找到一个有效分割即可,提前退出内层循环break;}}}// 返回整个字符串s是否可拆分returnf[n];}}