# 第一个只出现一次的字符
# 一、题目描述
在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例: s = "abaccdeff" 返回 "b"
s = "" 返回 " "
# 二、解题思路
思路1: 用一个map存储每个字符出现的字数
第一次循环存储次数,第二次循环找到第一个出现一次的字符。
时间复杂度O(n)、空间复杂度O(n)
#思路二: 使用js的array提供的indexOf和lastIndexOf方法
遍历字符串,比较每个字符第一次和最后一次出现的位置是否相同。
indexOf的时间复杂度为O(n),所以整体的时间复杂度为O(n2),空间复杂度为0
# 代码
思路一:
function FirstNotRepeatingChar(str) {
if (!str) {
return -1;
}
let countMap = {};
const array = str.split('');
const length = str.length;
for (let i = 0; i < length; i++) {
const current = array[i];
let count = countMap[current];
if (count) {
countMap[current] = count + 1;
} else {
countMap[current] = 1;
}
}
for (let i = 0; i < length; i++) {
if (countMap[array[i]] === 1) {
return i;
}
}
return -1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
思路二:
function FirstNotRepeatingChar(str) {
// write code here
for (var i = 0; i < str.length; i++) {
if (str.indexOf(str[i]) == str.lastIndexOf(str[i])) {
return i;
}
}
return -1;
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9