题目链接:https://leetcode-cn.com/problems/re-space-lcci/submissions/
思路:字典树实现倒序查找+dp
class Solution {
struct Tree
{
bool flag;
Tree* child[26]={nullptr};
Tree()
{
flag=false;
}
};
public:
int respace(vector<string>& dictionary, string sentence) {
int len=dictionary.size();
int len_sentence=sentence.size();
int dp[len_sentence+1];
fill(&dp[0],&dp[len_sentence],INT_MAX);
dp[0]=0;
Tree* head=new Tree();
for(auto word:dictionary)
{
Tree* cur_pos=head;
int len=word.size();
for(int i=len-1;i>=0;i--)
{
if(cur_pos->child[word[i]-'a']==nullptr)
{
cur_pos->child[word[i]-'a']=new Tree();
}
cur_pos= cur_pos->child[word[i]-'a'];
}
cur_pos->flag=true;
}
for(int i=1;i<=len_sentence;i++)
{
Tree* temp=head;
dp[i]=dp[i-1]+1;
for(int j=i;j>=1;j--)
{
int t=sentence[j-1]-'a';
if(temp->child[t]==nullptr)
break;
if(temp->child[t]->flag==true)dp[i]=min(dp[i],dp[j-1]);
if(dp[i]==0)break;
temp=temp->child[t];
}
}
return dp[len_sentence];
}
};