博客
关于我
Shortest Prefixes(trie树唯一标识)
阅读量:621 次
发布时间:2019-03-13

本文共 1270 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要找到每个给定单词的最短前缀,这个前缀必须唯一地标识该单词。也就是说,这个前缀应该是这个单词的最短开始部分,使得没有其他单词在输入集中以这个前缀开始。

方法思路

  • 读取输入:首先,我们读取所有输入的单词,并将它们存储在一个列表中。
  • 构建前缀哈希表:使用一个字典来记录每个前缀及其对应的单词数量。键是前缀,值是一个列表,包含所有以该前缀开头的单词。
  • 处理每个单词:对于每个单词,生成其所有可能的前缀,从最长到最短(即从长度为n到1)。检查每个前缀是否在哈希表中对应的单词数量为1。如果满足条件,那么这个前缀就是该单词的最短前缀。
  • 解决代码

    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字典中。
  • 处理每个单词:对于每个单词,生成其所有可能的前缀,按从长到短的顺序检查每个前缀。如果找到一个前缀在哈希表中对应的单词数量为1,则输出该前缀。否则,输出整个单词本身作为前缀。
  • 这种方法确保了我们能够高效地找到每个单词的最短前缀,并且保证了这个前缀的唯一性。

    转载地址:http://nueaz.baihongyu.com/

    你可能感兴趣的文章
    Oracle面试题:Oracle中truncate和delete的区别
    查看>>
    ThreadLocal线程内部存储类
    查看>>
    thinkphp 常用SQL执行语句总结
    查看>>
    Oracle:ORA-00911: 无效字符
    查看>>
    Text-to-Image with Diffusion models的巅峰之作:深入解读 DALL·E 2
    查看>>
    TCP基本入门-简单认识一下什么是TCP
    查看>>
    tableviewcell 中使用autolayout自适应高度
    查看>>
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>
    org.tinygroup.serviceprocessor-服务处理器
    查看>>