剑指offer——50. 第一个只出现一次的字符位置

50. 第一个只出现一次的字符位置

NowCoder

题目描述

在一个字符串中找到第一个只出现一次的字符,并返回它的位置。

1
2
Input: abacc
Output: b

解题思路

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
思路: O(2n)
用一个unordered_map遍历string,键值对《char, int count出现个数》;
遍历哈希,找到第一个值为一的数据
**/
class Solution {
public:
char firstNotRepeatingChar(string s) {
char res = '#';
if(s.empty()) return res;
unordered_map<char, int> dat;
for(auto x : s)
{
dat[x] ++; //不能break;后面的数据有可能也重复 必须轮询完
}
for(auto x : s)
{
if(dat[x] == 1)
{
res = x;
break;
}
}
return res;
}
};
创作不易,欢迎打赏!
-------------本文结束感谢您的阅读-------------