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]
- 易语言读取文本文件并显示到超级列表框:代码示例与注意要点(DeepSeek | 571点数解答 | 2025-08-23 20:54:40)224
- 易语言:读取并显示特定文本到超级列表框,还能增加新数据的方法与要点(DeepSeek | 1317点数解答 | 2025-08-23 20:58:40)230
- C++ 求解:最少操作次数让字符串无子串 “friend” (字节豆包 | 153点数解答 | 2024-08-17 16:29:54)478
- C++ 求解:最少操作次数让字符串不再含 “friend” 子串!(讯飞星火 | 260点数解答 | 2024-08-17 16:30:49)464
- Python 巧解:最少操作次数让字符串告别“friend”子串(字节豆包 | 139点数解答 | 2024-08-18 13:04:14)401
- 3414 数字游戏:Python 求解 8 位 01 字符串中 1 的个数 (字节豆包 | 106点数解答 | 2024-10-27 14:23:27)426
- 巧用字符添加,计算字符串中“our”最大数量及开发注意要点(DeepSeek | 376点数解答 | 2025-10-30 19:20:06)78
- C 语言实现:处理字符串生成最多 “our” 串,附代码及关键开发注意点 (DeepSeek | 257点数解答 | 2025-10-30 19:20:36)107
- Python 运行报错:urllib3 网络连接创建失败,原因及排查建议(字节豆包 | 161点数解答 | 2024-10-31 00:39:36)458
- mallshop商城网站:数据库设计与强大业务功能全揭秘(GPT | 257点数解答 | 2024-12-09 14:08:15)275
- Python 实战:学生信息列表转字典、遍历、深拷贝及数据修改全流程(GPT | 422点数解答 | 2024-10-29 15:43:54)414
- Python实战:学生成绩列表转字典,深拷贝与数据修改操作全解析(字节豆包 | 254点数解答 | 2024-10-29 16:01:39)405