# 字符流中第一个不重复的字符
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例:
s = "abaccdeff"
返回 "b"
s = ""
返回 " "
1
2
3
4
5
2
3
4
5
# 代码
解法一:前后索引相同
/**
* @param {string} s
* @return {character}
*/
var firstUniqChar = function(s) {
for (let i = 0; i < s.length; i++) {
if (s.lastIndexOf(s[i]) == s.indexOf(s[i])) return s[i];
}
return ' ';
};
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
解法二:哈希表统计法(true/false)
注意:Map的遍历会按添加顺序来
/**
* @param {string} s
* @return {character}
*/
var firstUniqChar = function(s) {
if (!s) return ' ';
let map = new Map();
for (c of s) {
if (map.has(c)) {
map.set(c, false);
} else {
map.set(c, true); // 是否只出现过一次
}
}
for (c of s) {
if (map.get(c)) return c;
}
return ' ';
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20