1
1
from typing import List
2
- import utils .datasets
3
2
from functools import lru_cache
4
3
4
+ # Method: DFS, prefix and best-of-rest with lookup against dict
5
+ # Time: O(n^2)
6
+ # Space: O(n)
7
+
8
+
5
9
def add_spaces (alltext : str , words : List [str ]):
6
10
word_set = set (words )
7
11
space_arr , invalids = add_spaces_helper (alltext , 0 , word_set , {})
8
12
9
- print (f"Managed to do it with { invalids } characters unknown, splits { space_arr } " )
13
+ # print(f"Managed to do it with {invalids} characters unknown, splits {space_arr}")
10
14
i = 0
11
15
spaced_text = []
12
16
for i in range (len (alltext )):
13
17
spaced_text .append (alltext [i ])
14
18
if i in space_arr :
15
19
spaced_text .append (" " )
16
-
17
20
18
21
return "" .join (spaced_text )
19
22
20
23
21
- def add_spaces_helper (text : str ,
22
- start_poz : int ,
23
- # split_pozs: List[int],
24
- word_set : set ,
25
- memo :dict ):
26
- if (start_poz in memo ):
24
+ def add_spaces_helper (
25
+ text : str ,
26
+ start_poz : int ,
27
+ word_set : set ,
28
+ memo : dict ,
29
+ ):
30
+ if start_poz in memo :
27
31
return memo [start_poz ]
28
-
32
+
29
33
n = len (text )
30
34
if start_poz == n :
31
35
return [], 0
@@ -41,13 +45,14 @@ def add_spaces_helper(text: str,
41
45
42
46
if invals < best_invals :
43
47
44
- rest_words , rest_invals_count = \
45
- add_spaces_helper (text , i + 1 , word_set , memo )
48
+ rest_words , rest_invals_count = add_spaces_helper (
49
+ text , i + 1 , word_set , memo
50
+ )
46
51
47
52
if rest_invals_count + invals < best_invals :
48
- current_splits = [start_poz - 1 , i ] if invals == 0 else []
53
+ current_splits = [start_poz - 1 , i ] if invals == 0 else []
49
54
best_invals = rest_invals_count + invals
50
- best_words = rest_words + current_splits
55
+ best_words = rest_words + current_splits
51
56
52
57
# print(f"At start {start_poz} Got best words {best_words}, and invals {best_invals}")
53
58
memo [start_poz ] = (best_words , best_invals )
@@ -56,11 +61,7 @@ def add_spaces_helper(text: str,
56
61
57
62
58
63
if __name__ == "__main__" :
59
- exs = [
60
- "helplinustechtipsineedtorebootmypc" ,
61
- "linusz" ,
62
- "torebootmy"
63
- ]
64
+ exs = ["helplinustechtipsineedtorebootmypc" , "linusz" , "torebootmy" ]
64
65
65
66
# words = utils.datasets.get_system_word_list()
66
67
words = ["help" , "tech" , "tips" , "boot" , "my" , "reboot" , "need" , "to" , "linus" ]
0 commit comments