Guest User

Untitled

a guest
Dec 12th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. class Solution:
  2. def build_trie(self, words):
  3. root = {}
  4. count = 0
  5. for word in words:
  6. parent = root
  7. for ch in word:
  8. count += 1
  9. if ch in parent:
  10. parent = parent[ch]
  11. else:
  12. parent[ch] = {}
  13. parent = parent[ch]
  14. else:
  15. parent["$"] = count
  16. count = 0
  17. return root
  18.  
  19. def in_trie(self, trie, word):
  20. parent = trie
  21. for ch in word:
  22. if ch not in parent:
  23. return parent.get('$', 0)
  24. else:
  25. parent = parent[ch]
  26. else:
  27. return parent.get('$', 0)
  28.  
  29. def addBoldTag(self, s, dic):
  30. cache = [0] * len(s)
  31. result = []
  32. trie = self.build_trie(dic)
  33.  
  34. for idx in range(len(s)):
  35. count = self.in_trie(trie, s[idx:])
  36. for c in range(count):
  37. cache[idx+c] = 1
  38.  
  39. status = 0
  40.  
  41. for idx, flag in enumerate(cache):
  42. if flag and not status:
  43. result.append("<b>")
  44. result.append(s[idx])
  45. status = 1
  46. elif not flag and status:
  47. result.append("</b>")
  48. result.append(s[idx])
  49. status = 0
  50. else:
  51. result.append(s[idx])
  52. else:
  53. if status:
  54. result.append("</b>")
  55.  
  56. return "".join(result)
Add Comment
Please, Sign In to add comment