不使用hashmap的方法,直接,效率不高
//找到字符数组中第一个只出现一次字符的位置
int FirstNotRepeatingChar(string str)
{
if (str=="")
return -1;
int Cstr[52] = {0};//统计可能出现的字母的次数:a-z,A-Z
for (int i=0; i<str.size(); i++)//统计每个字母出现的次数
{
if (str[i]>=65 && str[i]<=90)//A-Z
Cstr[str[i]-65]++;//大写字母坐标映射到0-25
if (str[i]>=97 && str[i]<=122)//a-z
Cstr[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
//使用map
int 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;
}
}