本文已参与[新人创作礼]活动,一起开启掘金创作之路
题目描述
139. 单词拆分
给你一个字符串 s 和一个字符串列表 wordDict 作为字典。请你判断是否可以利用字典中出现的单词拼接出 s 。
注意:不要求字典中出现的单词全部都使用,并且字典中的单词可以重复使用。
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"] 输出: true 解释: 返回 true 因为 "leetcode" 可以由 "leet" 和 "code" 拼接成。
提示:
1 <= s.length <= 300 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 20 s 和 wordDict[i] 仅有小写英文字母组成 wordDict 中的所有字符串 互不相同
问题解析
说到单词and找前缀,就是字典树的活了。
我们可以先把wordDict的元素都存入字典树中,然后用字符串s在字典树里找,初始下标为start,如果找到了有以当前位置为结尾的字符串,我们就把s切开,从设置下一个位置为start开始重新在字典树里找。如果在找的过程中,在字典树找不到了,说明不能以这个start为起点,我们返回false,并回到上一层(回溯),然后继续上一层之前的位置继续在字典树里找,找下一个以我们找到的位置为结尾的字符串。
当start为s的末尾时,说明我们已经找到了所有的字符串,这些字符串可以组合成s,返回true,反之我们输出false。
AC代码
const int N=1e4;
class Solution {
public:
int f[N][26],cnt[N],idx=1;
string str;
int n;
unordered_map<int,int>mymap;
void insert(string s)
{
int p=1;
for(auto i:s)
{
int j=i-'a';
if(f[p][j]==0)f[p][j]=++idx;
p=f[p][j];
}
cnt[p]=1;
}
bool dfs(int p,int start)
{
if (mymap[start] != 0)return false;
else if (start - 1 == n)return true;
int ans = p;
bool flag = false;
for (int i = start; i <= n; i++)
{
int j = str[i - 1] - 'a';
if (f[ans][j] == 0)break;
ans = f[ans][j];
if (cnt[ans] != 0)
{
flag = (flag || dfs(1,i+1));
if (flag)return flag;
}
}
mymap[start] = 1;
return false;
}
bool wordBreak(string s, vector<string>& wordDict) {
memset(f,0,sizeof f);
memset(cnt,0,sizeof cnt);
idx=1;
str=s;
n=str.size();
for(auto i:wordDict)insert(i);
return dfs(1,1);
}
};