-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
first-non-repeating-character.js
44 lines (36 loc) · 1.18 KB
/
first-non-repeating-character.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
function firstNonRepeatingLetter(s) {
if (!s) return '';
const counts = Array.prototype.reduce.call(s, (counts, letter) => {
letter = letter.toLowerCase();
counts[letter] = counts[letter] || 0;
counts[letter]++;
return counts;
}, {});
return Array.prototype.find.call(s, (letter) => {
return counts[letter.toLowerCase()] === 1;
}) || '';
}
function firstNonRepeatingLetter(s) {
if (!s) return '';
const counts = Array.prototype.reduce.call(s, (counts, letter) => {
letter = letter.toLowerCase();
counts.set(letter, (counts.get(letter) || 0) + 1);
return counts;
}, new Map());
// make this work...
// for (let [letter, count] of counts) {
// if (count === 1) {
// return letter;
// }
// }
return Array.prototype.find.call(s, (letter) => {
return counts[letter.toLowerCase()] === 1;
}) || '';
}
function firstNonRepeatingLetter(s) {
const sCaseless = s.toLowerCase();
return s[sCaseless.split('').findIndex(c => sCaseless.lastIndexOf(c) === sCaseless.indexOf(c))] || '';
}
console.log(firstNonRepeatingLetter('a'), 'a');
console.log(firstNonRepeatingLetter('stress'), 't');
console.log(firstNonRepeatingLetter('sTreSS'), 'T');