forked from Divya063/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bold-words-in-string.py
71 lines (62 loc) · 1.99 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
# 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
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
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 xrange(len(S)):
curr = trie
k = -1
for j in xrange(i, len(S)):
if S[j] not in curr:
break
curr = curr[S[j]]
if "_end" in curr:
k = j
for j in xrange(i, k+1):
lookup[j] = True
result = []
for i in xrange(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 xrange(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)