標籤:style class blog code color get
題目:在字串中找出第一個只出現一次的字元
題解分析:用空間換時間,使用雜湊表,key為字元,value是該字元出現的次數
字元是一個長度為8的資料類型,因此總共只有256種可能,我們可以建立一個長為256的數組,
每個字元根據其ASCII碼值作為數組的下標,即雜湊表的key,而相應數組位置儲存每個字元出現的次數,即雜湊表的value
char GetFirstOnce(const char* str) { assert(str != NULL); const int hashSize = 256; int hash[hashSize] = { 0 }; const char* cur = str; while (*cur != ‘\0‘) { hash[*cur]++; ++cur; } cur = str; while (*cur != ‘\0‘) { if (hash[*cur] == 1) { return *cur; } ++cur; } return ‘\0‘;}
相關問題:
1. 輸入兩個字串,從第一個字串中刪除在第二個字串中出現過的所有字元
void Delete(char* str1, const char* str2) { assert(str1 != NULL || str2 != NULL); const int hashSize = 256; int hash[hashSize] = { 0 }; const char* cur2 = str2; while (*cur2 != ‘\0‘) { hash[*cur2] = 1; ++cur2; } char* cur1 = str1; while (*str1 != ‘\0‘) { if (hash[*str1] == 0) { // 沒有出現在str2中,依次儲存 *cur1 = *str1; ++cur1; } ++str1; } *cur1 = ‘\0‘;}
2. 刪除字串中重複出現的字元,例如 “google”,執行函數之後應該是“gole”
首先將雜湊表中所有value設為false,第一次掃描到‘g‘時,ASCII碼下標對應的value為false,表示第一次出現,加入到res中,然後將value設為true,其後掃描到‘g‘時直接跳過
void DelDup(char* str) { assert(str != NULL); const int hashSize = 256; bool hash[hashSize] = { false }; char* cur = str; char* res = str; while (*cur != ‘\0‘) { if (hash[*cur] == false) { *res = *cur; ++res; hash[*cur] = true; } ++cur; } *res = ‘\0‘;}