File tree 1 file changed +49
-0
lines changed
solution/387.First Unique Character in a String
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ const firstUniqChar2 = function ( s ) {
2
+ let arr = { } ;
3
+ for ( let i = 0 ; i < s . length ; i ++ ) {
4
+ // console.log(arr[s[i]]);
5
+ if ( arr [ s [ i ] ] ) {
6
+ arr [ s [ i ] ] ++ ;
7
+ } else {
8
+ arr [ s [ i ] ] = 1 ;
9
+ }
10
+ }
11
+ let keys = Object . keys ( arr ) ;
12
+ for ( let i = 0 ; i < keys . length ; i ++ ) {
13
+ if ( arr [ keys [ i ] ] !== 1 ) {
14
+ keys . splice ( i , 1 ) ;
15
+ i -- ;
16
+ }
17
+ }
18
+ for ( let i = 0 ; i < s . length ; i ++ ) {
19
+ for ( let j = 0 ; j < keys . length ; j ++ ) {
20
+ if ( s [ i ] === keys [ j ] ) {
21
+ return i ;
22
+ }
23
+ }
24
+ }
25
+ return - 1 ;
26
+ }
27
+
28
+ const firstUniqChar = function ( s ) {
29
+ let hashTable = { } ;
30
+ let arr = [ ] ;
31
+
32
+ for ( let i = 0 ; i < s . length ; i ++ ) {
33
+ let c = s . charAt ( i ) ;
34
+ if ( ! hashTable . hasOwnProperty ( c ) ) {
35
+ hashTable [ c ] = i ;
36
+ arr . push ( i ) ;
37
+ } else {
38
+ if ( hashTable [ c ] !== null ) {
39
+ let val = hashTable [ c ] ;
40
+ let index = arr . indexOf ( val ) ;
41
+ arr . splice ( index , 1 ) ;
42
+ hashTable [ c ] = null ;
43
+ }
44
+ }
45
+
46
+ }
47
+
48
+ return arr . length ? arr [ 0 ] : - 1 ;
49
+ }
You can’t perform that action at this time.
0 commit comments