[算法] 定義一個函數,刪除字符串中所有重複出現的字符。
例如輸入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