传统思路 就是遍历字符串,访问某个字符时和后面的每个字符对比,如果没有重复就返回,如果有就向后遍历;这种时间复杂度为O(n*n);空间O(1);
新颖: 利用哈希表,把字符串的ASCII码作为Key,在字符串出现的次数作为value 然后遍历两次字符串即可得到结果;
代码:
int FirstNotRepeatingChar(string str) {
if(str.size()==0)
return -1;
//每个字符占8位共有256种可能
int hash[256];
for(int i=0;i<256;i++)
hash[i]=0;
int index=0;
while(str[index]!='\0'){
hash[str[index]]++;
index++;
}
index=0;
while(str[index]!='\0'){
if(hash[str[index]]==1)
return index;
index++;
}
return -1;
}