-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConcatenated_words(leetcode).cpp
32 lines (29 loc) · 1.13 KB
/
Concatenated_words(leetcode).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
Space complexity:
The space complexity is O(n * L), where n is the number of words in the input list and L is the maximum length of the words. The main source of the space complexity is the dp array, which is created for each word and has a size of L. Additionally, creating a unordered_set of all the words also takes O(n) space.
Code
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_set<string> words_set;
for (string word : words) words_set.insert(word);
vector<string> res;
for (string word : words) {
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 && words_set.count(word.substr(i, j - i))) {
dp[j] = 1;
}
}
if (dp[n]) {
res.push_back(word);
break;
}
}
}
return res;
}
};