-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0616-add-bold-tag-in-string.py
More file actions
33 lines (29 loc) · 944 Bytes
/
0616-add-bold-tag-in-string.py
File metadata and controls
33 lines (29 loc) · 944 Bytes
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
# time complexity: O(n*m)
# space complexity: O(n)
from typing import List
class Solution:
def addBoldTag(self, s: str, words: List[str]) -> str:
bold = [0] * len(s)
for word in words:
start = 0
while start < len(s):
idx = s.find(word, start)
if idx >= 0:
bold[idx:idx + len(word)] = [1] * len(word)
start = idx + 1
else:
break
result = []
for i, c in enumerate(s):
if bold[i] and (i == 0 or not bold[i - 1]):
result.append('<b>')
result.append(c)
if bold[i] and (i == len(s) - 1 or not bold[i + 1]):
result.append('</b>')
return "".join(result)
s = "abcxyz123"
words = ["abc", "123"]
print(Solution().addBoldTag(s, words))
s = "aaabbb"
words = ["aa", "b"]
print(Solution().addBoldTag(s, words))