-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconcatenated-words.cpp
75 lines (59 loc) · 1.55 KB
/
concatenated-words.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
struct TrieNode {
TrieNode* child[26];
bool isEnd;
TrieNode() {
for (int i = 0; i < 26; i++) {
child[i] = NULL;
}
isEnd = false;
}
};
class Trie {
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* curr = root;
for (auto c : word) {
int x = c - 'a';
if (curr->child[x] == NULL)
curr->child[x] = new TrieNode();
curr = curr->child[x];
}
curr->isEnd = true;
}
bool concat(string& str, int idx, int cnt) {
if (idx == (int)str.size())
return cnt >= 2;
TrieNode* curr = root;
for (int i = idx; i < (int)str.size(); i++) {
int x = str[i] - 'a';
if (curr->child[x] == NULL)
return false;
curr = curr->child[x];
if (curr->isEnd)
if (concat(str, i + 1, cnt + 1))
return true;
}
return false;
}
};
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
Trie tx;
for (auto x : words) {
tx.insert(x);
}
vector<string> ans;
for (auto str : words) {
int n = str.size();
if (tx.concat(str, 0, 0))
ans.push_back(str);
}
return ans;
}
};