-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_472.py
More file actions
36 lines (31 loc) · 1.13 KB
/
task_472.py
File metadata and controls
36 lines (31 loc) · 1.13 KB
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
from typing import List
from collections import deque
class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
st = set()
for w in words:
st.add(w)
#check if w can be made of given words
def check(w: str) -> bool:
n = len(w)
next = deque([-1])
while next:
start = next.pop()
for i in range(start+1, n):
if w[start+1:i+1] in st or w[start+1:i+1] in found:
next.append(i)
if i == n-1:
return True
return False
#find concatenated words
ans = []
found = set()
for w in words:
st.remove(w)
if check(w):
ans.append(w)
found.add(w)
st.add(w)
return ans
print(Solution().findAllConcatenatedWordsInADict(words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]))
print(Solution().findAllConcatenatedWordsInADict(words = ["cat","dog","catdog"]))