Skip to content

Commit 96a775c

Browse files
authored
Update add-bold-tag-in-string.py
1 parent 19c2edd commit 96a775c

File tree

1 file changed

+41
-2
lines changed

1 file changed

+41
-2
lines changed

Python/add-bold-tag-in-string.py

+41-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
# Time: O(s * d * l), l is the average string length
2-
# Space: O(s)
1+
# Time: O(n * d * l), l is the average string length
2+
# Space: O(n)
33

4+
# 59ms
45
class Solution(object):
56
def addBoldTag(self, s, dict):
67
"""
@@ -23,3 +24,41 @@ def addBoldTag(self, s, dict):
2324
if lookup[i] and (i == len(s)-1 or not lookup[i+1]):
2425
result.append("</b>");
2526
return "".join(result)
27+
28+
29+
# Time: O(n * l), l is the average string length
30+
# Space: O(t) , t is the size of trie
31+
# trie solution, 439ms
32+
class Solution2(object):
33+
def addBoldTag(self, s, words):
34+
"""
35+
:type s: str
36+
:type words: List[str]
37+
:rtype: str
38+
"""
39+
_trie = lambda: collections.defaultdict(_trie)
40+
trie = _trie()
41+
for i, word in enumerate(words):
42+
reduce(dict.__getitem__, word, trie).setdefault("_end")
43+
44+
lookup = [False] * len(s)
45+
for i in xrange(len(s)):
46+
curr = trie
47+
k = -1
48+
for j in xrange(i, len(s)):
49+
if s[j] not in curr:
50+
break
51+
curr = curr[s[j]]
52+
if "_end" in curr:
53+
k = j
54+
for j in xrange(i, k+1):
55+
lookup[j] = True
56+
57+
result = []
58+
for i in xrange(len(s)):
59+
if lookup[i] and (i == 0 or not lookup[i-1]):
60+
result.append("<b>")
61+
result.append(s[i])
62+
if lookup[i] and (i == len(s)-1 or not lookup[i+1]):
63+
result.append("</b>");
64+
return "".join(result)

0 commit comments

Comments
 (0)