题目
给你一个 不含重复 单词的字符串数组 words ,请你找出并返回 words 中的所有 连接词 。
连接词 定义为:一个完全由给定数组中的至少两个较短单词组成的字符串。
输入:words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
输出:["catsdogcats","dogcatsdog","ratcatdogcat"]
解释:
"catsdogcats" 由 "cats", "dog" 和 "cats" 组成;
"dogcatsdog" 由 "dog", "cats" 和 "dog" 组成;
"ratcatdogcat" 由 "rat", "cat", "dog" 和 "cat" 组成。
来源:力扣(LeetCode)
解答
此题一般用单词链接前缀树(字典树)来完成。
通过前缀树来完成单词的存在查询。
整体思路如下:
由于单词组成一定是短构成长,所以先对传入的单词数组进行排序,短单词在前,长单词在后。
第二步,依次遍历单词数组,对每一个单词进行连接判定,如果符合条件,就加入到返回数组中。如果不符合条件,就是一个完全“独立”的单词,就加入到前缀树中。
判定是否由多个单词进行连接,通过遍历前缀树,“魔改”search方法,通过一个标志位,来判定搜索到了单词的哪一部分,如果遍历了一个完整的单词,就重新进入遍历方法,但是标志位移动到下一个单词“接壤”的部分,继续遍历。遍历到最后,就可以得到是否能够完成连接。
class Trie {
public:
bool isEnd;
Trie *children[26];
/** Initialize your data structure here. */
Trie() {
isEnd = false;
memset(children, 0, sizeof(children));
}
/** Inserts a word into the trie. */
void insert(string word) {
auto p = this;
for (auto i: word) {
if (p->children[i - 'a'] == nullptr) {
p->children[i - 'a'] = new Trie();
}
p = p->children[i - 'a'];
}
p->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
auto p = this;
for (auto i: word) {
p = p->children[i - 'a'];
if (!p) {
return false;
}
}
return p->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
auto p = this;
for (auto i: prefix) {
p = p->children[i - 'a'];
if (!p) {
return false;
}
}
return true;
}
};
class Solution {
public:
Trie *t;
vector<string> findAllConcatenatedWordsInADict(vector<string> &words) {
vector<string> ret;
t = new Trie();
sort(words.begin(), words.end(), [](string a, string b) {
if (a.size() < b.size()) {
return true;
} else {
return false;
}
});
for (auto i: words) {
if (i.empty()) {
continue;
}
if (dfs(i, 0)) {
ret.push_back(i);
} else {
t->insert(i);
}
}
for (auto i: words) {
if (i.empty()) {
continue;
}
}
return ret;
}
bool dfs(string &s, int start) {
int n = s.size();
if (start == n) {
return true;
}
Trie *p = this->t;
for (int i = start; i < n; ++i) {
if (p->children[s[i] - 'a'] == nullptr) {
return false;
}
p = p->children[s[i] - 'a'];
if (p->isEnd) {
if (dfs(s, i + 1)) {
return true;
}
}
}
return false;
}
};