I'm doing an algorithm on Codesignal.
For s = "abacabad"
, the output should be firstNotRepeatingCharacter(a) = 'c'
.
There are 2 non-repeating characters in the string: 'c' and 'd'. Return c since it appears in the string first.
For s = "abacabaabacaba"
, the output should be firstNotRepeatingCharacter(s) = '_'
.
There are no characters in this string that do not repeat.
Code below:
function firstNotRepeatingCharacter(a) {
let b = {};
let len = a.length;
for (let i = 0; i < len; i++) {
let tmp = a.charAt(i);
if (b[tmp]) {
b[tmp] += 1; //explain here
}
else {
b[tmp] = 1;
}
}
for (var prop in b) {
if (b[prop] == 1) { //explain here
return prop;
}
}
return '_';
}
Actually in the above b
is an object whose keys are different letters of the string and the values of those keys are count of respective lettter in the string.
key => letter
value => Count of that letter
tmp
will be character through you are iterating.
if (b[tmp])
checks whether the letter is already added to the object.
In the second loop if (b[prop] == 1)
checks whether the count of certain letter is 1
. means that it only occurred once in the string so return the letter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.