第一个只出现一次的字符

来源:互联网 发布:mysql 连接池大小 编辑:程序博客网 时间:2024/05/17 01:17


不使用hashmap的方法,直接,效率不高

//找到字符数组中第一个只出现一次字符的位置int FirstNotRepeatingChar(string str) {if (str=="")return -1;int Cstr[52] = {0};//统计可能出现的字母的次数:a-z,A-Zfor (int i=0; i<str.size(); i++)//统计每个字母出现的次数{if (str[i]>=65 && str[i]<=90)//A-ZCstr[str[i]-65]++;//大写字母坐标映射到0-25if (str[i]>=97 && str[i]<=122)//a-zCstr[str[i]-97+26]++;//小写字母坐标映射到26-51}vector<char> ch;for (int i=0; i<52; i++)//找到出现次数为{if (1==Cstr[i]){if (i>=26)ch.push_back(i-26+97);else ch.push_back(i+65);}}vector<char>::iterator it;for (int i=0; i<str.size(); i++){for (it=ch.begin();it!=ch.end(); it++){if (*it==str[i]) {cout << i <<": "<<*it <<endl;return i;}}}}


使用map

//使用mapint FirstNotRepeatingCharMap(string str){if (str=="")return -1;map<char,int> mp;for (int i=0; i<str.size(); i++){mp[char(str[i])]++;}map<char,int>::iterator it;for (int i=0; i<str.size(); i++){for (it=mp.begin(); it!=mp.end(); it++){if (it->second == 1 && it->first==str[i]) {cout << i <<": "<< it->first <<endl;return i;}}}}


使用hash_map

int FirstNotRepeatingChar2(string str) {if (str=="")return -1;const int tablesize = 256;unsigned int hashtable[tablesize];for (unsigned int i=0; i<tablesize; i++)hashtable[i] = 0;for (int i=0; i<str.size(); i++){hashtable[str[i]]++;}for (int i=0; i<str.size(); i++){if (hashtable[str[i]] == 1)return i;}}


0 0