Leetcode 472 Solution

This article provides solution to leetcode question 472 (concatenated-words)

https://leetcode.com/problems/concatenated-words

Solution

class Solution { public: vector<string> findAllConcatenatedWordsInADict(vector<string>& words) { vector<string> res; unordered_set<string> wordDict(words.begin(), words.end()); for (int i = 0; i < words.size(); i++) { auto word = words[i]; if (word.empty()) continue;
wordDict.erase(words[i]);
bool dp[word.size() + 1]; memset((void*)dp, 0, word.size() + 1); dp[0] = true;
for (int i = 0; i <= word.size(); i++) { if (dp[i] == false) continue;
for (int j = i; j < word.size(); j++) if (wordDict.find(word.substr(i, j - i + 1)) != wordDict.end()) dp[j + 1] = 1;
if (dp[word.size()]) { res.push_back(word); break; } }
wordDict.insert(word); }
return res; } };