-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path387_First_Unique_Character_in_a_String.js
More file actions
71 lines (63 loc) · 1.89 KB
/
387_First_Unique_Character_in_a_String.js
File metadata and controls
71 lines (63 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Note: You may assume the string contain only lowercase letters.
*/
const expect = require('expect');
describe('387 First Unique Character in a String', () => {
it('returns the index of the first non-repeating character', () => {
//arragne
const input = 'abcabc';
const expected = -1;
//act
const actual = firstUniqChar(input);
//assert
expect(actual).toBe(expected);
});
it('returns the index of the first non-repeating character', () => {
//arragne
const input = 'leetcode';
const expected = 0;
//act
const actual = firstUniqChar(input);
//assert
expect(actual).toBe(expected);
});
it('returns the index of the first non-repeating character', () => {
//arragne
const input = 'loveleetcode';
const expected = 2;
//act
const actual = firstUniqChar(input);
//assert
expect(actual).toBe(expected);
});
});
const firstUniqChar_1 = (string) => {
const hash = {};
[...string].forEach((char, index) => {
if (!hash[char] && hash[char] !== 0) hash[char] = index;
else {
hash[char] = true;
}
});
const nonRepeatingIndex = Object.values(hash)
.filter(value => typeof value !== 'boolean')
.sort((prev, next) => prev - next)
.shift();
if (nonRepeatingIndex === undefined) return -1;
return nonRepeatingIndex;
};
const firstUniqChar_2 = (string) => {
const recordArray = [];
[...string].forEach(value => {
const codeIndex = value.charCodeAt(0) - 97;
if (!recordArray[codeIndex]) recordArray[codeIndex] = 1;
else { recordArray[codeIndex] += 1; }
});
for (const [index, value] of [...string].entries()) {
const codeIndex = value.charCodeAt(0) - 97;
if (recordArray[codeIndex] === 1) return index;
}
return -1;
};