Last active
December 12, 2018 09:04
-
-
Save fortable1999/9a92cbf578607e229026f903c6a9d58e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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