Skip to content

Commit 3ea6874

Browse files
committed
feat: add first uniq char
1 parent d5a8b3f commit 3ea6874

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

js/first_uniq_char.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-03-24 22:33:31
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-03-24 22:35:16
6+
*/
7+
8+
// 字符串中的第一个唯一字符 https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xn5z8r/
9+
/**
10+
* 387. 字符串中的第一个唯一字符
11+
* 给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
12+
*
13+
* 示例:
14+
* s = "leetcode"
15+
* 返回 0
16+
*
17+
* s = "loveleetcode"
18+
* 返回 2
19+
* 提示:你可以假定该字符串只包含小写字母。
20+
*
21+
*/
22+
23+
// 利用hash表存储数量进行计数,然后再进行一次计算
24+
const firstUniqChar = (s) => {
25+
let cacheMap = {};
26+
27+
for (let i = 0, len = s.length; i < len; i++) {
28+
const value = s[i];
29+
30+
cacheMap[value] =
31+
typeof cacheMap[value] !== "undefined" ? cacheMap[value] + 1 : 1;
32+
}
33+
34+
for (let i = 0, len = s.length; i < len; i++) {
35+
if (cacheMap[s[i]] === 1) {
36+
return i;
37+
}
38+
}
39+
40+
return -1;
41+
};
42+
43+
console.log(firstUniqChar("leetcode")); // 0
44+
console.log(firstUniqChar("loveleetcode")); // 2
45+
console.log(firstUniqChar("aadadaad")); // -1

0 commit comments

Comments
 (0)