Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b67eec3

Browse files
Merge pull request MisterBooo#1 from MisterBooo/master
更新项目
2 parents d6c6cc7 + 2b1a3c2 commit b67eec3

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
5.99 MB
Binary file not shown.
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
# 387. 字符串中的第一个唯一字符
2+
3+
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。
4+
>
5+
> 同步博客:https://www.algomooc.com
6+
7+
题目来源于 LeetCode 上 387题,主要涉及哈希表。
8+
9+
## 题目
10+
11+
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
12+
13+
案例:
14+
15+
```
16+
s = "leetcode"
17+
返回 0.
18+
19+
s = "loveleetcode",
20+
返回 2.
21+
```
22+
23+
注意事项:您可以假定该字符串只包含小写字母。
24+
25+
## 题目解析
26+
27+
这道题不管怎么样都是要遍历一遍字符串才能保证字符是唯一,所以我们的算法如下
28+
29+
1. 遍历的时候把每个字符出现的次数用Map记录一下,如果这个字符是第一次出现,那么赋值为[i],如果它已经在Map里有了,那么我们给这个字符的值赋为false。
30+
2. 再次遍历Map,找到值不为false的第一个字符,然后将它的值输出来
31+
3. 如果值全部为false,然后返回-1
32+
33+
34+
## 动画理解
35+
36+
37+
<video id="video" controls="" preload="none" >
38+
<source id="mp4" src="../Animation/387.mp4" type="video/mp4">
39+
</video>
40+
41+
## 参考代码
42+
43+
44+
```javaScript
45+
/**
46+
* @param {string} s
47+
* @return {number}
48+
*/
49+
var firstUniqChar = function(s) {
50+
let map = new Map()
51+
for (let i = 0; i < s.length;i++) {
52+
if(map.has(s[i])) {
53+
map.set(s[i], false)
54+
}else {
55+
map.set(s[i], [i])
56+
}
57+
}
58+
for(let item of map){
59+
if (item[1]) {
60+
return item[1][0]
61+
}
62+
}
63+
return -1
64+
};
65+
```
66+
67+
## 复杂度分析
68+
69+
哈希表的时间复杂度是O(n)
70+
71+
72+
![](../../Pictures/qrcode.jpg)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /