I was looking through leetcode and found problem with a solution I couldn't quite reason through.
Description of problem: "Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'."
Solution:
/*test word*/ var word = "abcdefghijklmnopqrstuvwxyziflskecznslkjfabe";
/*Test #2 var word = "abacabad"; */
firstNotRepeatingChar = s => {
var arr = s.split("");
for(var i = 0; i < arr.length; i++){
if(arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i]))
return arr[i];
}
return "_"
};
firstNotRepeatingChar(word);
I was wondering if i could have someone explain how this works and why it comes out the solution of "d". Test # 2 should print "c", which it does, but I don't fully understand why.
Many thanks!