给你一个字符串 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
思路:动态规划
此题正着想,应该判断当前由wordDcit中的单词拼出来的字串path是不是s的前缀串,最终返回true时,应该为path等于s,但是判断前缀要用KMP,时间复杂度很高。
所以要倒着想,判断s中的s[i..j]这一子串是不是wordDict中的单词,这样时间复杂度就降下来了
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n=s.size();
unordered_set<string> st;
for(auto& word:wordDict) {
st.insert(word);
}
//dp[i]表示s[..i]是否可以由wordDict中的单词拼接而成
vector<bool> dp(n+1);
dp[0]=true;//s=""时,无需拼接
for(int i=1;i<=n;i++) {
//枚举分割点,将s[..i]分成s[..j]和s[j+1..i]
for(int j=0;j<i;j++) {
//s[..j]可以由wordDict中的单词拼出来
if(dp[j]) {
//判断s[j+1..i]是不是wordDict中的单词
if(st.count(s.substr(j,i-j))) {
dp[i]=true;
break;//可以拼出来就立刻终止循环
}
}
dp[i]=false;
}
}
return dp[n];
}
};
给定一个字符串 s
和一个字符串字典 wordDict
,在字符串 s
中增加空格来构建一个句子,使得句子中所有的单词都在词典中。以任意顺序 返回所有这些可能的句子。
注意:词典中的同一个单词可能在分段中被重复使用多次。
示例 1:
输入:s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] 输出:["cats and dog","cat sand dog"]
示例 2:
输入:s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] 输出:["pine apple pen apple","pineapple pen apple","pine applepen apple"] 解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] 输出:[]
思路:回溯
判断子串s[start...i]是否为字典wordDict中的单词
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> st;
for(auto& word:wordDict)
{
st.insert(word);
}
vector<string> res;
function<void(int,string&)> backtrack=[&](int start,string& path)
{
if(start==s.size())
{
path.pop_back();//去掉最后的" "
res.push_back(path);
return ;
}
for(int i=start;i<s.size();i++)//枚举子串终点
{
string cur=s.substr(start,i-start+1);
if(st.count(cur))
{
string temp=path;
path+=cur+" ";
backtrack(i+1,path);//回溯
path=temp;
}
}
};
string path;
backtrack(0,path);
return res;
}
};