本题有两个经典操作:
- 在“句子”中提取出所有“单词”(用空格分开子字母字符串、用字母分开数字字符串或相反):双指针-当找到“单词”首字符时,进入while找到尾字符,于是首位指针指向索引的区间,就是整个单词;(tip: 注意找单词外的循环中Index和右指针的关系);
- 字符串哈希表使用;
- 注意:使用全局变量一定要在每次函数执行前,清零,否则会带着上一次执行测试用例留下的数据,导致各种奇怪现象,比如力扣输出和本地输出不一样、对同一个测试用例,力扣提交输出和单独做测试用例输出不一致等;
- 对数字、单词等建立“映射”有几种方式:一维数组、二维数组(数字)/指针数组(字符串)、哈希表、结构体等,当要记录的多,且涉及“查找”、“添加”、“删除”时,适合用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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。