给定一个非空字符串 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
解法:
动态规划,dp[i]表示s的前i个字符[0 ... i-1 ]是否可以由字典中的单词组成,那么状态转移方程为
dp[i]=d[i-j]&check(word),类似走楼梯,在匹配的过程可以用哈希表实现,或者字典树。
bool wordBreak(string s, vector<string>& wordDict) {
//return wordSearch(s, wordDict, "");
unordered_map<string, int> ma;
int max_len = 0;
for (auto &word : wordDict)
{
ma[word] = 1;
int wlen = word.length();
if (wlen > max_len)//记录最大的单词长度
max_len = wlen;
}
int len = s.length();
vector<int> dp(len+1);
dp[0] = 1;
for (int i = 1; i <= len; i++)
{
dp[i] = 0;
string str ="";
for (int j = 1; j <= max_len&&i-j>=0; j++)
{
str = s[i - j]+str;
if (dp[i - j]&&ma[str])
{
dp[i] = 1;
}
}
}
return dp[len] == 1;
}
超时解法:
用dfs,用字典中的单词去拼凑目标字符串,由于没用哈希表去缩短匹配时间,所以超时。
class Solution {
bool wordSearch(const string &s, vector<string> &wordDict, string str)
{
if(str==s)return true;
if(str.length()>=s.length())return false;
if(str!=s.substr(0, str.length()))return false;
bool ans=false;
for(auto word:wordDict)
{
ans=ans|wordSearch(s, wordDict, str+word);
if(ans)
return true;
}
return ans;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
return wordSearch(s, wordDict, "");
}
};
这篇博客探讨了如何利用动态规划算法解决一个字符串能否被字典中的单词拆分的问题。给出的示例代码展示了如何通过构建状态转移方程和使用哈希表来优化查找过程,从而避免超时。此外,还提到了一个超时的解决方案,即使用深度优先搜索(DFS),但由于没有使用哈希表加速,导致效率低下。
1593

被折叠的 条评论
为什么被折叠?



