• 请不要在回答技术问题时复制粘贴 AI 生成的内容
microxiaoxiao
V2EX  ›  程序员

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

  •  
  •   microxiaoxiao · Jul 12, 2022 · 1272 views
    This topic created in 1403 days ago, the information mentioned may be changed or developed.

    有经验的大佬来指教一下

    3 replies    2022-07-13 10:23:27 +08:00
    amlee
        1
    amlee  
       Jul 12, 2022
    hashmap , key 存字符串 hash ,value 存数组 index
    CEBBCAT
        2
    CEBBCAT  
       Jul 12, 2022 via iPhone
    重新描述一下根本问题呗?
    vvtf
        3
    vvtf  
       Jul 13, 2022
    **后续还需要根据这 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));
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3034 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 06:45 · PVG 14:45 · LAX 23:45 · JFK 02:45
    ♥ Do have faith in what you're doing.