- 题目:在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
- 思路:
- 用一个map,记录每一个字符第一次出现的index,如果出现两次,index改成-1
- 遍历不是-1的map找到最小的index,如果没找到返回-1,找到了返回index
- 启发或者坑
- 考虑到所有的情况,有可能字符串里面没有只出现一次的字符
- 代码
class Solution { public: int FirstNotRepeatingChar(string str) { //用一个map,记录每一个字符第一次出现的index,如果出现两次,index改成-1 //遍历不是-1的map找到最小的index,如果没找到返回-1,找到了返回index map<char, int> mark; map<char, int>::iterator it; for (int i = 0; i < str.length(); i++) { it = mark.find(str.at(i)); if (it == mark.end()) { mark.insert(pair<char,int>(str.at(i), i)); } else { mark[it->first] = -1; } } int res = str.length(); for (it=mark.begin(); it!=mark.end(); ++it) { if (it->second != -1 && res > it->second) res = it->second; } if (res == str.length()) res = -1; return res; } };
剑指offer 33.第一个只出现一次的字符
猜你喜欢
转载自blog.csdn.net/Alexia23/article/details/103866501
今日推荐
周排行