-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconcat_wrds.py
36 lines (33 loc) · 1.29 KB
/
concat_wrds.py
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 collections import deque
class Solution:
def __dfs_check (self, word, words):
q, visited = deque([0]), [False for i in range(len(word) + 1)]
visited[0] = True
while (q):
start = q.popleft()
for end in range(start + 1, len(word) + 1):
if (word[start:end] in words):
if (end == len(word)): return True
if (not visited[end]):
q.append(end)
visited[end] = True
return False
def __bfs_check (self, word, words):
q, visited = deque([0]), [False for i in range(len(word) + 1)]
visited[0] = True
while (q):
start = q.popleft()
for end in range(start + 1, len(word) + 1):
if (word[start:end] in words):
if (end == len(word)): return True
if (not visited[end]):
q.append(end)
visited[end] = True
return False
def findAllConcatenatedWordsInADict (self, words: List[str]) -> List[str]:
words, res = set(words), []
for word in words:
words.remove(word)
if (self.__bfs_check(word, words)): res.append(word)
words.add(word)
return res