-
Notifications
You must be signed in to change notification settings - Fork 44
/
bold-words-in-string.py
90 lines (74 loc) · 2.65 KB
/
bold-words-in-string.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
Given a set of keywords words and a string S, make all appearances of all keywords in S bold. Any letters between <b> and </b> tags become bold.
The returned string should use the least number of tags possible, and of course the tags should form a valid combination.
For example, given that words = ["ab", "bc"] and S = "aabcd", we should return "a<b>abc</b>d". Note that returning "a<b>a<b>b</b>c</b>d" would use more tags, so it is incorrect.
Note:
words has length in range [0, 50].
words[i] has length in range [1, 10].
S has length in range [0, 500].
All characters in words[i] and S are lowercase letters.
"""
# Time: O(n * l), n is the length of S, l is the average length of words
# Space: O(t) , t is the size of trie
# V0
# V1
# DEV
# V2
# Time: O(n * l), n is the length of S, l is the average length of words
# Space: O(t) , t is the size of trie
import collections
import functools
class Solution(object):
def boldWords(self, words, S):
"""
:type words: List[str]
:type S: str
:rtype: str
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
for i, word in enumerate(words):
functools.reduce(dict.__getitem__, word, trie).setdefault("_end")
lookup = [False] * len(S)
for i in range(len(S)):
curr = trie
k = -1
for j in range(i, len(S)):
if S[j] not in curr:
break
curr = curr[S[j]]
if "_end" in curr:
k = j
for j in range(i, k+1):
lookup[j] = True
result = []
for i in range(len(S)):
if lookup[i] and (i == 0 or not lookup[i-1]):
result.append("<b>")
result.append(S[i])
if lookup[i] and (i == len(S)-1 or not lookup[i+1]):
result.append("</b>")
return "".join(result)
# Time: O(n * d * l), l is the average length of words
# Space: O(n)
class Solution2(object):
def boldWords(self, words, S):
"""
:type words: List[str]
:type S: str
:rtype: str
"""
lookup = [0] * len(S)
for d in words:
pos = S.find(d)
while pos != -1:
lookup[pos:pos+len(d)] = [1] * len(d)
pos = S.find(d, pos+1)
result = []
for i in range(len(S)):
if lookup[i] and (i == 0 or not lookup[i-1]):
result.append("<b>")
result.append(S[i])
if lookup[i] and (i == len(S)-1 or not lookup[i+1]):
result.append("</b>")
return "".join(result)