酷代码 AI
菜单
服务商

Python:用前缀树统计字符串数组中以前缀开头的元素数量

```python class PrefixTree: def __init__(self): self.table = [0] * 26 self.next = None def insert(self, s): current = self for ch in s: index = ord(ch) - ord('a') current.table[index] += 1 if current.next is None: current.next = PrefixTree() current = current.next def count(self, s): current = self total_count = 0 for ch in s: index = ord(ch) - ord('a') if current.table[index] == 0: return 0 total_count += current.table[index] if current.next is None: return total_count current = current.next return total_count def count_prefix(words, prefix): tree = PrefixTree() for word in words: tree.insert(word) return tree.count(prefix) words = ["apple", "apricot", "banana", "ape"] prefix = "ap" print(count_prefix(words, prefix)) ``` ######[AI写代码神器 | 259点数解答 | 2024-10-26 14:44:39]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]