本文共 1427 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要判断给定的电话号码列表是否一致,即没有电话号码是另一个号码的前缀。我们可以使用前缀树(trie)结构来高效地解决这个问题。
class TrieNode: def __init__(self): self.children = {} self.is_end = Falsedef is_consistent(numbers): root = TrieNode() for num in numbers: current = root for c in num: digit = int(c) if digit not in current.children: current.children[digit] = TrieNode() current = current.children[digit] if current.is_end: return False current.is_end = True return Truedef main(): import sys input = sys.stdin.read().split() ptr = 0 t = int(input[ptr]) ptr += 1 for _ in range(t): n = int(input[ptr]) ptr +=1 numbers = [] for _ in range(n): num = input[ptr].strip() ptr +=1 numbers.append(num) if is_consistent(numbers): print("YES") else: print("NO")if __name__ == "__main__": main()
这种方法的时间复杂度是O(n * 10),其中n是电话号码的数量,10是电话号码的最大长度,能够高效处理题目中的输入规模。
转载地址:http://xueaz.baihongyu.com/