STEP #1

(1/2)

此处切换ai服务商,可对比多家ai的回复,取最优解。

上一步下一步关闭
酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

输入字符串数组words,每个字符串中间有且仅有一个空格,输入字符串prefix。输出在words中以prefix为前缀的数量。 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

```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)) ``` [2024-10-26 14:44:39 | AI写代码神器 | 259点数解答]
相关提问