网址:www.nowcoder.com/practice/1c…
描述
在一个长为 字符串中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
数据范围:0 \le n \le 100000≤n≤10000,且字符串只有字母组成。
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
public:
int FirstNotRepeatingChar(string str) {
map<char,int> m;
int l=str.size();
for(int i=0;i<l;i++)
{
if(m.find(str[i])!=m.end())
{
m[str[i]]=11000;
}
else m[str[i]]=i;
}
int ans=11000;
for(auto &v : m)
{
ans=min(ans,v.second);
}
if (ans==11000)
return -1;
return ans;
}
};
总结:
要知道是否出现了一次,就要把出现过的字符保存下来,或者记录下出现的字符的次数,或者记录下出现过的字符的索引位置,当该字符再次出现,就把这个字符标记下来。不能删除,如果删除了,再次出现的话会判定为以前没有出现过。
函数:
iterator find( const KEY_TYPE &key );
map中的find()函数返回一个[迭代器]()指向键值为key的元素,如果没找到就返回指向map尾部的[迭代器]()。
map的遍历:
map<int,int> m;
//第一种
for(auto &t : m)
{
cout<<t.first<<t.second<<endl;
}
//第二种
map<int,int>::iterator it;
for(iter = m.begin(); iter != m.end(); ++iter)
{
cout<<iter->first<<iter->second<<endl;
}