/**************************************
*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 編程藝術系列