题目描述
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = "leetcode" 返回 0. s = "loveleetcode", 返回 2.
注意事项:您可以假定该字符串只包含小写字母。
问题分析
先用哈希map保存字符串中字母与出现次数的映射,然后遍历字符串,当遍历到某字母在哈希map中的值为1时,返回其索引,当遍历结束仍未返回,返回-1。
代码实现
class Solution {
public:
int firstUniqChar(string s) {
int ans = INT_MAX;
unordered_map<char, int> umap;
for(char c : s)
++umap[c];
for(int i = 0; i < s.size(); i++)
if(umap[s[i]] == 1)
return i;
return -1;
}
};