| 18 | """ |
| 19 | |
| 20 | class TrieNode(object): |
| 21 | # __slots__ 考虑到TrieNode会大量创建,使用 __slot__来减少内存的占用。 |
| 22 | # 在测试的15个例子中: |
| 23 | # 使用 __slots__会加快创建,平均的耗时为290ms-320ms。 |
| 24 | # 而不使用则在 340ms-360ms之间。 |
| 25 | # 创建的越多效果越明显。 |
| 26 | # 当然,使用字典而不是类的方式会更加更加更加高效。 |
| 27 | __slots__ = {'value', 'nextNodes', 'breakable'} |
| 28 | |
| 29 | def __init__(self, value, nextNode=None): |
| 30 | self.value = value |
| 31 | if nextNode: |
| 32 | self.nextNodes = [nextNode] |
| 33 | else: |
| 34 | self.nextNodes = [] |
| 35 | self.breakable = False |
| 36 | |
| 37 | def addNext(self, nextNode): |
| 38 | self.nextNodes.append(nextNode) |
| 39 | |
| 40 | def setBreakable(self, enable): |
| 41 | self.breakable = enable |
| 42 | |
| 43 | def __eq__(self, other): |
| 44 | return self.value == other |
| 45 | |
| 46 | |
| 47 | |