暴力法
思路,外层循环确定待比较的字符,内层循环将每个字符与带比较的字符,进行比较。定义一个计数器count,初始化为1。最后输出count仍为1对应的位置即可。
class Solution {
public:
int FirstNotRepeatingChar(string str) {
for(int i=0;i<str.size();i++)
{ char temp = str[i];
int count =1;
for(int j=0;j<str.size();j++)
{
if(i!=j)
{ if(temp==str[j])
{
count++;
break; //出现两个相同,没有必要找下去了
}
}
}
if(count==1)
return i;
}
return -1;
}
};
2 hash表
将每个字符与出现的次数存入hash表中,再找出次数为1的位置即可。
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.size()==0) return -1;
unordered_map<char, int> map;
for(int i=0;i<str.size();i++)
map[str[i]]++;
for(int i=0;i<str.size();i++)
{
if(map[str[i]]==1)
return i;
}
return -1;
}
};
3.利用str函数 :find_first_of()和 find_last_of()
具体用法可百度。假定该函数参数为cha c,find_first_of() 是找出 str中第一个出现该字符c的位置,
同理,find_last_of() 是找出 str中最后一次出现该字符c的位置。
可想象,我们遍历该字符串,当某一次字符的find_first_of() 和find_last_of() 返回值均为该字符的下标时,说明该字符只出现了一次。
class Solution {
public:
int FirstNotRepeatingChar(string str) {
for(int i=0;i<str.size();i++)
{ if(str.find_first_of(str[i])==i &&str.find_last_of(str[i])==i)
return i;
}
return -1;
}
};