找出字符串中第一个不重复的字符(JavaScript实现)
如题~
此算法仅供参考,小菜基本不懂高深的算法,只能用最朴实的思想去表达。
1 //找出字符串中第一个不重复的字符 2 // firstUniqueChar("vdctdvc"); --> t 3 function firstUniqueChar(str){ 4 var str = str || "", 5 i = 0, 6 k = "", 7 _char = "", 8 charMap = {}, 9 result = {name: "",index: str.length}; 10 11 for(i=0;i<str.length;i++){ 12 _char = str.charAt(i); 13 if(charMap[_char] != undefined){ 14 charMap[_char] = -1; 15 }else{ 16 charMap[_char] = i; 17 } 18 } 19 20 for(k in charMap){ 21 if(charMap[k]<0){ 22 continue; 23 } 24 if(result.index>charMap[k]){ 25 result.index = charMap[k]; 26 result.name = k; 27 } 28 } 29 30 return result.name; 31 }