劍指offer (35) 第一個只出現一次的字元 字元雜湊表

來源:互聯網
上載者:User

標籤: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‘;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.