@@ -50,8 +50,7 @@ def word_break(string: str, words: list[str]) -> bool:
50
50
...
51
51
ValueError: the words should be a list of non-empty strings
52
52
"""
53
-
54
- # Validation
53
+
55
54
if not isinstance (string , str ) or len (string ) == 0 :
56
55
raise ValueError ("the string should be not empty string" )
57
56
@@ -60,22 +59,25 @@ def word_break(string: str, words: list[str]) -> bool:
60
59
):
61
60
raise ValueError ("the words should be a list of non-empty strings" )
62
61
63
-
64
- # Build trie
65
- trie : dict [str , Any ] = {}
66
62
word_keeper_key = "WORD_KEEPER"
67
63
68
- for word in words :
69
- trie_node = trie
70
- for c in word :
71
- if c not in trie_node :
72
- trie_node [c ] = {}
64
+ # Helper function to build the trie
65
+ def build_trie (words : list [str ]) -> dict [str , Any ]:
66
+ trie : dict [str , Any ] = {}
73
67
74
- trie_node = trie_node [c ]
68
+ for word in words :
69
+ trie_node = trie
70
+ for c in word :
71
+ if c not in trie_node :
72
+ trie_node [c ] = {}
73
+ trie_node = trie_node [c ]
74
+ trie_node [word_keeper_key ] = True
75
75
76
- trie_node [ word_keeper_key ] = True
76
+ return trie
77
77
78
- len_string = len (string )
78
+ # Build trie
79
+ trie = build_trie (words )
80
+ strLength = len (string )
79
81
80
82
# Dynamic programming method
81
83
@functools .cache
@@ -85,17 +87,17 @@ def is_breakable(index: int) -> bool:
85
87
>>> is_breakable(1)
86
88
True
87
89
"""
88
- if index == len_string :
90
+ if index == strLength :
89
91
return True
90
92
91
93
trie_node = trie
92
- for i in range (index , len_string ):
93
- trie_node = trie_node .get (string [i ], None )
94
+ for letter in range (index , strLength ):
95
+ trie_node = trie_node .get (string [letter ], None )
94
96
95
97
if trie_node is None :
96
98
return False
97
99
98
- if trie_node .get (word_keeper_key , False ) and is_breakable (i + 1 ):
100
+ if trie_node .get (word_keeper_key , False ) and is_breakable (letter + 1 ):
99
101
return True
100
102
101
103
return False
0 commit comments