-
Notifications
You must be signed in to change notification settings - Fork 0
/
Q13_re_space.py
50 lines (39 loc) · 1.51 KB
/
Q13_re_space.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
import unittest
class Result:
def __init__(self, parsed=" ", invalid=float("inf")):
self.parsed = parsed
self.invalid = invalid
def re_space(words, s):
dp = [None] * len(s)
def split_words(start):
if start >= len(s):
return Result("", 0)
if not dp[start]:
best_invalid = float("inf")
best_parsing = None
idx = start
word = ""
while idx < len(s):
word += s[idx]
invalid = len(word) if word not in words else 0
if invalid <= best_invalid:
result = split_words(idx + 1)
if invalid + result.invalid <= best_invalid:
best_invalid = invalid + result.invalid
if result.parsed != "":
best_parsing = word + " " + result.parsed
else:
best_parsing = word
if best_invalid == 0:
break
idx += 1
dp[start] = Result(best_parsing, best_invalid)
return dp[start]
return split_words(0)
class Test(unittest.TestCase):
def test_re_space(self):
words = set(["looked", "just", "like", "her", "brother"])
sentence = "jesslookedjustliketimherbrother"
result = re_space(words, sentence)
self.assertEqual(7, result.invalid)
self.assertEqual("jess looked just like tim her brother", result.parsed)