且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[算法] 定义一个函数,删除字符串中所有重复出现的字符。

更新时间:2022-02-18 09:55:20

例如输入google,输出gole

思路:

利用一个hash table用来记录输入字符串中每次字符出现的次数,如果不是0,再复制,如果是1,则跳过。需要新开辟一个数组用来存储新的字符。

char * DeleteRepeat(const char *string){
     if(string == NULL)
               return '\0';
     int *array = new int[256];
     //initilize the array
     for(int i = 0; i<256; i++){
             array[i] = 0;        
     }     
     //calculate the length of the string
     int length = 0;
     const char* current = string;
     while(*current != '\0'){
                    length++;
                    current++;               
     }
     char *result  = new char[length+1];
     current = string;
     char *p = result;
     while(*current!= '\0'){
                    if(array[*current]==1){
                              current++;                       
                    }                 
                    else if(array[*current] == 0){
                         *(p++) = *current;
                         array[*current++] = 1;     
                    }
     }
     *p= '\0';
     return result;
}