-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0758-bold-words-in-string.py
More file actions
36 lines (29 loc) · 936 Bytes
/
0758-bold-words-in-string.py
File metadata and controls
36 lines (29 loc) · 936 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
34
35
36
# time complexity: O(n*m)
# space complexity: O(n)
from typing import List
class Solution:
def boldWords(self, words: List[str], S: 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)
words = ["ab", "bc"]
s = "aabcd"
print(Solution().boldWords(words, s))
words = ["ab", "cb"]
s = "aabcd"
print(Solution().boldWords(words, s))