利用哈希表进行字符处理的两个例子
输入两个字符串,从一个字符串中删除第二个字符串中的字符,用一个哈希表记录了第二个字符串中的字符
1 void delete_ch(char *src, char *del_chs) { 2 int hash[256]; 3 int i; 4 char *p_slow, *p_fast; 5 int del_len = strlen(del_chs); 6 p_slow = src; 7 p_fast = src; 8 memset(hash, 0, sizeof(int) * 256); 9 for (i = 0; i < del_len; i++) 10 hash[del_chs[i]] = 1; 11 while (*p_fast) { 12 if (hash[*p_fast] == 1) { 13 p_fast++; 14 } 15 *p_slow++ = *p_fast++; 16 } 17 *p_slow = '\0'; 18 }
定义一个函数,删除字符串中所有重复出现的字符,仍然利用哈希表记录字符串中已经出现的字符
1 void delete_repeatc(char *src) 2 { 3 if (src == NULL) 4 return; 5 int hashtable[256]; 6 for (int i = 0; i < 256; i++) 7 hashtable[i] = 0; 8 char *fast = src; 9 char *slow = src; 10 while (*fast != '\0') 11 { 12 if (hashtable[*fast] == 0) 13 { 14 *slow = *fast; 15 hashtable[*fast] = 1; 16 slow++; 17 } 18 fast++; 19 } 20 *slow = '\0'; 21 }

浙公网安备 33010602011771号