Skip to content

Commit a3d173c

Browse files
authored
Create 472.Concatenated-Words.cpp
1 parent a364a75 commit a3d173c

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
class Solution {
2+
class TrieNode
3+
{
4+
public:
5+
TrieNode* next[26];
6+
bool isEnd;
7+
TrieNode()
8+
{
9+
for (int i=0; i<26; i++)
10+
next[i] = NULL;
11+
isEnd = false;
12+
}
13+
};
14+
TrieNode* root;
15+
public:
16+
vector<string> findAllConcatenatedWordsInADict(vector<string>& words)
17+
{
18+
sort(words.begin(), words.end(), [](string&a, string&b){return a.size()<b.size();});
19+
root = new TrieNode();
20+
21+
vector<string>rets;
22+
for (auto word: words)
23+
{
24+
if (word!="" && check(word, root))
25+
rets.push_back(word);
26+
27+
TrieNode* node = root;
28+
for (auto ch:word)
29+
{
30+
if (node->next[ch-'a']==NULL)
31+
node->next[ch-'a'] = new TrieNode();
32+
node = node->next[ch-'a'];
33+
}
34+
node->isEnd = true;
35+
}
36+
return rets;
37+
}
38+
39+
bool check(string& word, TrieNode* root)
40+
{
41+
int n = word.size();
42+
vector<int>visited(n,0);
43+
return dfs(word, root, 0, visited);
44+
}
45+
46+
bool dfs(string& word, TrieNode* root, int cur, vector<int>&visited)
47+
{
48+
if (cur==word.size()) return true;
49+
50+
if (visited[cur]==1)
51+
return false;
52+
53+
TrieNode* node = root;
54+
55+
for (int i=cur; i<word.size(); i++)
56+
{
57+
if (node->next[word[i]-'a']!=NULL)
58+
{
59+
node = node->next[word[i]-'a'];
60+
if (node->isEnd && dfs(word, root, i+1, visited))
61+
return true;
62+
}
63+
else
64+
{
65+
break;
66+
}
67+
}
68+
69+
visited[cur] = 1;
70+
return false;
71+
}
72+
};

0 commit comments

Comments
 (0)