哈希的使用

来源:互联网 发布:网络信息安全协议书 编辑:程序博客网 时间:2024/05/16 13:40

1、问题:

 两个字符串A、B。从A中剔除存在于B中的字符。比如A=“hello world”,B="er",那么剔除之后A变为"hllowold"。空间复杂度要求是O(1),时间复杂度越优  越好。

2、分析:

用一个一定大小的数组记录B字符串中各个字符的存在;hash查找,空间要求O(1).

3、主要代码:

用一定长度的数组记录B字符串中各个字符的存在。

int hashChar[100];int charToInt(char c){     if(islower(c))           return c-'a';     else        return c - 'A' + 26;     }void charToHash(char *b){    for(int i = 0; b[i]; i ++)    {         hashChar[charToInt(b[i])] = 1;    }}

遍历A字符串中的各个字符,如果该字符在hashChar对应的位置为1,则代表要删除这个字符;删除过程,数组位置移位。

void delSameChar(char *a, char *b){    int pos, i, j;    while(a[i])    {         pos = charToInt(a[i]);         if(hashChar[pos])         {               for(j = i; a[j]; j ++)               {                     a[j] = a[j + 1]               }         }         i ++;    }}



0 0
原创粉丝点击