閱讀180 返回首頁    go 阿裏雲 go 技術社區[雲棲]


[算法] 定義一個函數,刪除字符串中所有重複出現的字符。

例如輸入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;
}

最後更新:2017-04-03 12:56:36

  上一篇:go mian函數參數用法
  下一篇:go 如何讓AlertDialog 在點擊確定或者取消時不消失