So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.
T
I came accross this while facing similar problem. Let me add my 2 lines.
What I did is a similar to the Guffa's answer. But using both indexOf
method and lastIndexOf
.
My mehod:
function nonRepeated(str) {
for(let i = 0; i < str.length; i++) {
let j = str.charAt(i)
if (str.indexOf(j) == str.lastIndexOf(j)) {
return j;
}
}
return null;
}
nonRepeated("aabcbd"); //c
Simply, indexOf()
gets first occurrence of a character & lastIndexOf()
gets the last occurrence. So when the first occurrence is also == the last occurence, it means there's just one the character.