TGViewer
JavaScript | LeetCode JavaScript | LeetCode @easy_frontend_task · 8.32K subscribers
Post #2197 786
Задача: 472. Concatenated Words
Сложность: hard

Дан массив строк words (без дубликатов). Верните все составные слова из данного списка слов.
Составное слово определяется как строка, которая полностью состоит как минимум из двух более коротких слов (не обязательно различных) из данного массива.

Пример:
Input: words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".


👨‍💻 Алгоритм:

1⃣Для каждого слова в списке:
Построить неявный граф, в котором узлы представляют индексы символов в слове, а ребра представляют возможность перехода от одного индекса к другому, если подстрока между ними является словом из списка.

2⃣Использовать поиск в глубину (DFS) для проверки, можно ли достигнуть узел с индексом word.length от узла с индексом 0 в графе.

3⃣Если узел word.length достижим от узла 0, добавить слово в ответ.

😎 Решение:
class Solution {
dfs(word, length, visited, dictionary) {
if (length === word.length) {
return true;
}
if (visited[length]) {
return false;
}
visited[length] = true;
for (let i = word.length - (length === 0 ? 1 : 0); i > length; i--) {
if (dictionary.has(word.slice(length, i)) && this.dfs(word, i, visited, dictionary)) {
return true;
}
}
return false;
}

findAllConcatenatedWordsInADict(words) {
const dictionary = new Set(words);
const answer = [];
for (const word of words) {
const visited = Array(word.length).fill(false);
if (this.dfs(word, 0, visited, dictionary)) {
answer.push(word);
}
}
return answer;
}
}

// Example usage
const solution = new Solution();
const words = ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"];
console.log(solution.findAllConcatenatedWordsInADict(words));


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_frontend_task
  1. Oct 11, 2026Задача: 651. 4 Keys Keyboard Сложность: medium Представьте, что у вас есть специальная кла…
  2. Oct 9, 2026Задача: 1054. Distant Barcodes Сложность: medium На складе имеется ряд штрих-кодов, где i-…
  3. Oct 9, 2026Задача: 1237. Find Positive Integer Solution for a Given Equation Сложность: medium Если д…
  4. Oct 8, 2026Задача: №19. Remove Nth Node From End of List Сложность: medium Дан связанный список и чис…
  5. Oct 7, 2026Задача: 1057. Campus Bikes Сложность: medium В городке, изображенном на плоскости X-Y, ест…
  6. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для Frontend разработчика, которые нигде больше не…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →