Skip to content

Instantly share code, notes, and snippets.

@fortable1999
Last active December 12, 2018 09:04
Show Gist options
  • Save fortable1999/9a92cbf578607e229026f903c6a9d58e to your computer and use it in GitHub Desktop.
Save fortable1999/9a92cbf578607e229026f903c6a9d58e to your computer and use it in GitHub Desktop.
class Solution:
def build_trie(self, words):
root = {}
count = 0
for word in words:
parent = root
for ch in word:
count += 1
if ch in parent:
parent = parent[ch]
else:
parent[ch] = {}
parent = parent[ch]
else:
parent["$"] = count
count = 0
return root
def in_trie(self, trie, word):
parent = trie
for ch in word:
if ch not in parent:
return parent.get('$', 0)
else:
parent = parent[ch]
else:
return parent.get('$', 0)
def addBoldTag(self, s, dic):
cache = [0] * len(s)
result = []
trie = self.build_trie(dic)
for idx in range(len(s)):
count = self.in_trie(trie, s[idx:])
for c in range(count):
cache[idx+c] = 1
status = 0
for idx, flag in enumerate(cache):
if flag and not status:
result.append("<b>")
result.append(s[idx])
status = 1
elif not flag and status:
result.append("</b>")
result.append(s[idx])
status = 0
else:
result.append(s[idx])
else:
if status:
result.append("</b>")
return "".join(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment