1. 程式人生 > >查詢字串中第一個只出現一次的字元

查詢字串中第一個只出現一次的字元

考研的時候學習過雜湊函式,但這只是書本上的知識,簡單的理解,從來沒用過,也不知道怎麼用,直到學了第一堂演算法課,原來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 ' ';

}