-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathfirstNonRepeatingCharacter.js
59 lines (50 loc) · 1.48 KB
/
firstNonRepeatingCharacter.js
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
function firstNonRepeatingCharWithMap(inputStr) {
if(inputStr.length === 0) return null;
let charCountsMap = new Map();
for(let ch of inputStr) {
charCountsMap.set(ch, (charCountsMap.get(ch) || 0) + 1);
}
for(let [key, value] of charCountsMap.entries()) {
if(value === 1) {
return key;
}
}
return null;
}
function firstNonRepeatingCharWithObj(inputStr) {
if(inputStr.length === 0) return null;
let charCountsObj = {};
for(let ch of inputStr) {
charCountsObj[ch] = (charCountsObj[ch] || 0) + 1;
}
for(let [key, value] of Object.entries(charCountsObj)) {
if(value === 1) {
return key;
}
}
return null;
}
/**---------------
All Unique
--------------- */
console.log("Input: 'abcdefgh'");
console.log("Output: ", firstNonRepeatingCharWithObj('abcdefgh'));
console.log("---------------");
/**---------------
Some Duplicates
--------------- */
console.log("Input: 'abccddefgggh'");
console.log("Output: ", firstNonRepeatingCharWithObj('abccddefgggh'));
console.log("---------------");
/** ---------------
All Duplicates
--------------- */
console.log("Input: 'aabbccdddeeeff'");
console.log("Output: ", firstNonRepeatingCharWithMap('aabbccdddeeeff'));
console.log("---------------");
/** ---------------
Empty String
--------------- */
console.log("Input: ''");
console.log("Output: ", firstNonRepeatingCharWithMap(''));
console.log("---------------");