![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3fb9de306f8417b8e0bd9c45cfd4f33c.png)
字典树
struct TrieNode
{
bool isEnd;
TrieNode *next[26];
TrieNode()
{
isEnd = false;
memset(next, 0, sizeof(next));
}
};
class Trie
{
TrieNode* root;
public:
Trie()
{
root = new TrieNode();
}
void add(string word)
{
TrieNode *node = root;
for(int i = 0; i < word.size(); i++)
{
char ch = word[i];
if(node->next[ch - 'a'] == NULL)
{
node->next[ch - 'a'] = new TrieNode();
}
node = node->next[ch - 'a'];
}
node->isEnd = true;
}
bool check(string& word,int count,int start)
{
TrieNode *node = root;
for(int i = start; i < word.size(); i++)
{
if(node->next[word[i] - 'a'] == NULL) return false;
node = node->next[word[i] - 'a'];
if(node->isEnd == true)
{
if(i == word.size()-1) return count >= 1;
if(check(word, count+1, i + 1)) return true;
}
}
return false;
}
};
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
Trie dict;
vector<string>res;
for(int i = 0; i < words.size(); i++)
{
dict.add(words[i]);
}
for(int i = 0; i < words.size(); i++)
{
if(dict.check(words[i], 0, 0) == true)
{
res.push_back(words[i]);
}
}
return res;
}
};
check那里:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8155c027cdee48d6015b302b806ee3e2.png)
bool check(string& word,int count,int start)
{
TrieNode *node = root;
for(int i = start; i < word.size(); i++)
{
if(node->next[word[i] - 'a'] == NULL) return false;
node = node->next[word[i] - 'a'];
if(node->isEnd == true)
{
if(i == word.size()-1) return count >= 1;
if(check(word, count+1, i + 1)) return true;
}
}
return false;
}