C算法-UT哈希+并查集

leetcode面试题 17.07. 婴儿名字。之前写过一篇根本不算HASH的HASH,现在借鉴了各位大神的UT哈希方法,把这个题目理一理。

思路如下:
1、通过info存取names的关键信息,本质就是比names多了cnt及root信息,用处是记录最终的cnt信息,以及给团队赋值为最小字典序(char *root)
2、通过hash存取names的关键信息,用处是支撑synonyms元素的快速查找对应索引位置HASH_FIND,将两个索引进行并查集处理

小知识点一:对字符串分割
names = [“John(15)”,“Jon(12)”,“Chris(13)”,“Kris(4)”,“Christopher(19)”]
synonyms = ["(Jon,John)","(John,Johnny)","(Chris,Kris)","(Chris,Christopher)"]
分割方法依次如下,其中对字符串的分割停止表达是:%[^ xxx], xxx就是想停止的字符

sscanf(names[i],"%[^(](%d)", info[i].name, &cnt);
sscanf(syn,"(%[^,],%[^)])", tmps[0], tmps[1]);

小知识点二:UT哈希方法
1、建立HASH
存放数据结构

typedef struct _info_st
{
   
    char name[STR_LEN];
    char *root;
    int cnt;
}info_st;

typedef struct _hash_st
{
   
    char *key;
    int id;
    UT_hash_handle hh;
}hash_st;

info_st *info;
hash_st *pool;
hash_st *head;

初始化

    pool = (hash_st *)malloc(namesSize * sizeof(hash_st));
    head = NULL;

2、查找&添加
遗留为什么这里用的HASH_FIND,如下链接总结了UT哈希

        hash_st *new = &pool[psize];
        new->key = info[i].name;
        new->id = i;

        hash_st *tmph;
        HASH_FIND_STR(head, new->key, tmph);
        if(tmph == NULL) {
   
            HASH_ADD_KEYPTR(hh, head, new->key, tmplen, new);
            psize++;            
        }

3、查找具体索引

        hash_st *tmph;
        HASH_FIND_STR(head, tmps[j], tmph
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值