查找字符串中第一個只出現一次的字符

考研的時候學習過哈希函數,但這只是書本上的知識,簡單的理解,從來沒用過,也不知道怎麼用,直到學了第一堂算法課,原來hash表可以用數組模擬,統計數字或字符出現的次數。


代碼如下:

int CHash::getStuNum(int* data, int len, int score){

if(data == NULL || len <= 0 || score < 0 || score > MAX_SCORE){

return ERROR;

}

//count each score 

int *scoreMap = new int[MAX_SCORE];

for(int i = 0; i < MAX_SCORE; i++){

scoreMap[i] = 0;

}

 

for(int i = 0; i < len; i ++){

scoreMap[data[i]] ++;//關鍵字映射到scoreMap中,關鍵字每出現一次,對應的的scoreMap[data[i]]加一;

}

 

int result = scoreMap[score];

delete[] scoreMap;

 

return result;

}

 //統計字符出現的頻率,本題是求第一個只出現一次的字符

char CHash::getFirstChar(char *str){

if(str == NULL){

return ' ';

}

 

const int CHAR_NUM = 256;

int *charMap = new int[CHAR_NUM];     //assic碼0-255;

for(int i = 0; i < CHAR_NUM; i++){

charMap[i] = 0;

}

char *p = str;

while( *p != '\0'){

charMap[*p] ++;      //字符隱式轉換成整形;

p++;

}

 

p = str;

while( *p != '\0'){

if(charMap[*p] == 1){

return *p;

}

p++;

}

 

delete[] charMap;

 

return ' ';

}


發佈了26 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章