在一個字串中找到第一個只出現一次的字元。

來源:互聯網
上載者:User

/**************************************

*copyright@ andy

*http://blog.csdn.net/MonkeyAndy

**************************************/

題目描述:

在一個字串中找到第一個只出現一次的字元。如輸入 abaccdeff,則輸出 b。


思路:

用hash表來儲存相應的字元,key為ch-‘a’, value為相應的出現的次數,遍曆字串,尋找對應的hash表中value為1所對應的字元


代碼如下:

/********如有您有任何疑問及發現問題,歡迎隨時指正********/

//copyright@andy#include <stdlib.h>#include <stdio.h>#include <string.h>#define TABLESIZE 26typedef struct HashTable{char *elem;int count;//當前hash表中的元素個數int size;//hash的容量}HashTable;HashTable h;void init_hash(){h.elem = (char*) malloc (sizeof(char) * TABLESIZE);if(!h.elem) exit(1);memset(h.elem, 0, TABLESIZE);h.count = 0;h.size = TABLESIZE;}char find_first_appear(char *string){int i;char *pstring = string;/*第一次遍曆字串,構建字串相應的hash表,key為 ch-'a' ,value 為相應的出現的個數*/while(*pstring != '\0'){h.elem[*(pstring++) - 'a']++;h.count++;}/*第二次遍曆字串,找到第一個出現一次的字元*/while(*string++ != '\0'){if(h.elem[*string - 'a'] == 1)return *string;}/*沒找到時,返回空*/return '\0';}int main(){char * string="abaccdeff";int i;init_hash();char first_appear = find_first_appear(string);for(i=0; i<TABLESIZE; i++)printf("%c ",'a'+i);printf("\n");for(i=0; i<TABLESIZE; i++)printf("%d ",h.elem[i]);printf("\n");printf("the current size of hash table is %d\n
           the fist appear char is %c\n",h.count, first_appear);return 0;}

參考自: http://blog.csdn.net/v_JULY_v   編程藝術系列 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.