The JavaScript implementation finds the first non repeating character in the string

  • 2020-03-30 03:49:16
  • OfStack

This algorithm is for reference only, the basic dishes do not understand the advanced algorithm, can only use the most simple ideas to express.


//Find the first non-repeating character in the string
// firstUniqueChar("vdctdvc"); --> t
function firstUniqueChar(str){
var str = str || "",
i = 0,
k = "",
_char = "",
charMap = {},
result = {name: "",index: str.length};

for(i=0;i<str.length;i++){
_char = str.charAt(i);
if(charMap[_char] != undefined){
charMap[_char] = -1;
}else{
charMap[_char] = i;
}
}

for(k in charMap){
if(charMap[k]<0){
continue;
}
if(result.index>charMap[k]){
result.index = charMap[k];
result.name = k;
}
}

return result.name;
}

Related articles: