题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
//只用一个9*52个字节,遍历一次就能找到,可以算得上最优解
int FirstNotRepeatingChar(string str) {
map<char,pair<int,int>> the_map;
for(int i=0;i<str.size();++i)
{
the_map[str[i]];
if(the_map[str[i]].first==0)
{
the_map[str[i]]=make_pair(1,i);
}
else
{
the_map[str[i]].first++;
}
}
int min=-1;
for(auto m:the_map)
{
if(m.second.first==1)
{
if(min==-1)min=m.second.second;
else if(min>m.second.second)min=m.second.second;
}
}
return min;
}
本文介绍了一种高效的算法,用于在一万个字符的字符串中找到第一个仅出现一次的字符,并返回其位置。通过使用字典结构,算法仅需遍历一次字符串即可完成任务。
492

被折叠的 条评论
为什么被折叠?



