-
Notifications
You must be signed in to change notification settings - Fork 0
/
word_break.py
53 lines (46 loc) · 900 Bytes
/
word_break.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# SHIV's code for word break
'''
2
12
i like sam sung samsung mobile ice cream icecream man go mango
ilike
12
i like sam sung samsung mobile ice cream icecream man go mango
idontlike
Non-Memoized:
1
0
finished in: 0.00020813941955566406
Memoized:
1
0
finished in: 7.009506225585938e-05
Crazyy!
'''
import time
tn = int(input())
memoize = {}
def solve(q, words):
if q in memoize: return memoize[q]
if len(q) == 1:
if q[0] in words: return 1
else: return 0
segments = []
for i in range(len(q)-1,0,-1):
left, right = q[:i], q[i:]
if solve(left, words) == 1:
segments.append(right)
for seg in segments:
if seg in words:
memoize[q] = 1
return memoize[q]
memoize[q] = 0
return memoize[q]
start = time.time()
for i in range(tn):
w_n = int(input())
words = input().split()
query = input()
ans = solve(query, words)
print(ans)
print("finished in: ", time.time()-start)