本文共 1296 字,大约阅读时间需要 4 分钟。
为了解决这个问题,我们需要找到每个给定单词的最短前缀,这个前缀必须唯一地标识该单词。也就是说,这个前缀应该是这个单词的最短开始部分,使得没有其他单词在输入集中以这个前缀开始。
import sysfrom collections import defaultdictdef main(): words = [] for line in sys.stdin: line = line.strip() if line: words.append(line) # Build prefix map prefix_map = defaultdict(list) for word in words: for i in range(len(word)): prefix = word[:i+1] prefix_map[prefix].append(word) # Process each word to find the minimal prefix for word in words: found = False for i in range(len(word)-1, -1, -1): prefix = word[:i+1] if len(prefix_map[prefix]) == 1: print(f"{word} {prefix}") found = True break if not found: print(f"{word} {word}")if __name__ == "__main__": main() sys.stdin读取输入,并将每行非空字符串添加到words列表中。prefix_map字典中。这种方法确保了我们能够高效地找到每个单词的最短前缀,并且保证了这个前缀的唯一性。
转载地址:http://nueaz.baihongyu.com/