File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments