-
Notifications
You must be signed in to change notification settings - Fork 0
/
concatWords.cpp
54 lines (49 loc) · 1.13 KB
/
concatWords.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
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
vector<string> findAllConcatenatedWords(vector<string> &words)
{
unordered_set<string> s;
vector<string> ans;
for (string i : words)
{
s.insert(i);
}
for (string word : words)
{
if (word.empty())
continue;
int n = word.size();
vector<int> dp(n + 1, 0);
dp[0] = 1;
for (int i = 0; i < n; i++)
{
if (!dp[i])
continue;
for (int j = i + 1; j <= n; j++)
{
if (j - i < n && s.count(word.substr(i, j - i)))
{
dp[j] = 1;
}
}
if (dp[n])
{
ans.push_back(word);
break;
}
}
}
return ans;
}
int main()
{
vector<string> words = {"cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"};
vector<string> ans = findAllConcatenatedWords(words);
for (string word : ans)
{
cout << word << endl;
}
return 0;
}