博客
关于我
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/

    你可能感兴趣的文章
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>