TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.01K subscribers
Post #1814 908
Задача: 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:
def dfs(self, word, length, visited, dictionary):
if length == len(word):
return True
if visited[length]:
return False
visited[length] = True
for i in range(len(word) - (1 if length == 0 else 0), length, -1):
if word[length:i] in dictionary and self.dfs(word, i, visited, dictionary):
return True
return False

def findAllConcatenatedWordsInADict(self, words):
dictionary = set(words)
answer = []
for word in words:
visited = [False] * len(word)
if self.dfs(word, 0, visited, dictionary):
answer.append(word)
return answer


Ставь 👍 и забирай 📚 Базу знаний
  • 👍 1
More from @easy_python_task
  1. Oct 15, 2026Задача: 1043. Partition Array for Maximum Sum Сложность: medium Если задан целочисленный м…
  2. Oct 15, 2026Задача: 1474. Delete N Nodes After M Nodes of a Linked List Сложность: easy Вам дано начал…
  3. Oct 15, 2026Post #2446
  4. Oct 14, 2026Задача: 977. Squares of a Sorted Array Сложность: easy Дан целочисленный массив nums, отсо…
  5. Oct 13, 2026Задача: 462. Minimum Moves to Equal Array Elements II Сложность: medium Дан массив целых ч…
  6. Oct 13, 2026Задача: 1056. Confusing Number Сложность: easy Запутанное число - это число, которое при п…
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 →