LeetCode-1805 字符串中不同整数的数目

在这里插入图片描述
在这里插入图片描述

本题有两个经典操作:

  1. 在“句子”中提取出所有“单词”(用空格分开子字母字符串、用字母分开数字字符串或相反):双指针-当找到“单词”首字符时,进入while找到尾字符,于是首位指针指向索引的区间,就是整个单词;(tip: 注意找单词外的循环中Index和右指针的关系);
  2. 字符串哈希表使用;
  3. 注意:使用全局变量一定要在每次函数执行前,清零,否则会带着上一次执行测试用例留下的数据,导致各种奇怪现象,比如力扣输出和本地输出不一样、对同一个测试用例,力扣提交输出和单独做测试用例输出不一致等;
  4. 对数字、单词等建立“映射”有几种方式:一维数组、二维数组(数字)/指针数组(字符串)、哈希表、结构体等,当要记录的多,且涉及“查找”、“添加”、“删除”时,适合用uthash哈希表;
#define NUM_MAX 1001

typedef struct {
    char numch[NUM_MAX];
    UT_hash_handle hh;
} NumHash;

NumHash *g_hashTbl = NULL;

void GetNum (char *word, int *in, char *numCh) {
    int begin = *in;
    int end = *in;

    while (word[end]>= '0' && word[end]<= '9') {
        end++;
    }
    end--;

    while (word[begin] == '0') {
        begin++;
    }

    strncpy(numCh, word + begin, end - begin + 1);
    numCh[end - begin + 1] = '\0';
    *in = end;

    return;
}

void UpdateCnt(char *numCh, int *cnt) {
    NumHash *tmp = NULL;
    int cntTmp = *cnt;
    HASH_FIND_STR(g_hashTbl, numCh, tmp);
    if (tmp == NULL) {
        tmp = (NumHash *)malloc(sizeof(NumHash));
        strcpy(tmp->numch, numCh);
        HASH_ADD_STR(g_hashTbl, numch, tmp);
        cntTmp++;
    }

    *cnt = cntTmp;
    return;
}

int numDifferentIntegers(char * word){
    char num[NUM_MAX];
    int index = 0;
    int cnt = 0;
    g_hashTbl = NULL;

    while (word[index] != '\0') {
        if (word[index] >= '0' && word[index] <= '9') {
            GetNum(word, &index, num);
            UpdateCnt(num, &cnt);
            //printf("%d-", cnt);
        }
        index++;
    }

    return cnt;
}

作者:Crystal
链接:https://leetcode.cn/problems/number-of-different-integers-in-a-string/solutions/2100188/c-ti-qu-dan-ci-ha-xi-biao-lian-xi-by-cry-ib0v/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值