V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
microxiaoxiao
V2EX  ›  程序员

字符串 hash 问题,有 <N 个字符串长度任意,放入到长度为 N 的数组,后续还需要根据这 N 个字符串快速得到位置,怎么样最快呢?

  •  
  •   microxiaoxiao · 2022-07-12 21:38:31 +08:00 · 791 次点击
    这是一个创建于 646 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有经验的大佬来指教一下

    3 条回复    2022-07-13 10:23:27 +08:00
    amlee
        1
    amlee  
       2022-07-12 21:43:29 +08:00
    hashmap , key 存字符串 hash ,value 存数组 index
    CEBBCAT
        2
    CEBBCAT  
       2022-07-12 23:59:35 +08:00 via iPhone
    重新描述一下根本问题呗?
    vvtf
        3
    vvtf  
       2022-07-13 10:23:27 +08:00
    **后续还需要根据这 N 个字符串快速得到位置**
    这句话看不懂, 找到位置有啥意义? 位置放的也是字符串....
    不过你的字面需求可以用一下代码试试:

    int index = 0;
    map<string, int> map;
    string[] arr;
    for ( str : strings) {
    string key = md5(str);
    int val = map.putIfAbsent(key, index);
    if (null != val) {
    continue;
    }
    arr[index ++] = str;
    }


    // get index by string
    return map.get(md5(str));
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5470 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 06:36 · PVG 14:36 · LAX 23:36 · JFK 02:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.