链接:472. 连接词
题解:力扣
class Solution {
private:
struct TrieTree {
char c;
bool end;
std::string word;
vector<TrieTree*> next;
TrieTree() {
end = false;
next.resize(26, nullptr);
}
};
TrieTree* _root;
private:
void insert_trie_tree(const std::string& word) {
TrieTree* cur = _root;
for (auto ch : word) {
if (cur->next[ch-'a'] == nullptr) {
cur->next[ch-'a'] = new (std::nothrow) TrieTree;
}
cur = cur->next[ch-'a'];
}
cur->end = true;
cur->word = word;
}
bool find_word(int begin, TrieTree* cur, const std::string& word, std::vector<std::string>& path) {
if (begin >= word.size()) {
if (cur == _root && path.size() >= 2) {
return true;
}
return false;
}
if (cur->next[word[begin]-'a'] == nullptr) {
return false;
}
cur = cur->next[word[begin]-'a'];
if (cur->end) {
path.push_back(cur->word);
if (find_word(begin+1, _root, word, path)) {
return true;
}
path.pop_back();
}
if (find_word(begin+1, cur, word, path)) {
return true;
}
return false;
}
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
std::vector<std::string> result;
if (words.size() <= 0) {
return result;
}
_root = new (std::nothrow) TrieTree;
sort(words.begin(), words.end(), [&](const string & a, const string & b){
return a.size() < b.size();
});
for (auto& word : words) {
int begin = 0;
std::vector<std::string> path;
if (word.size() == 0) {
continue;
}
TrieTree* cur = _root;
if (find_word(begin, cur, word, path)) {
result.push_back(word);
} else {
insert_trie_tree(word);
}
}
return result;
}
};