return the first non repeating character in a string in javascript

后端 未结 26 2227
清酒与你
清酒与你 2020-12-30 09:04

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

26条回答
  •  伪装坚强ぢ
    2020-12-30 09:31

    Here is one other solution just using array, using 26 unique character as length of array:

    var firstUniqChar = (function(s) {
        var arr = [];
        var str = s.toLowerCase();
        for(let c of str){
          let index = c.charCodeAt(0) - "a".charCodeAt(0);
          arr[index]? ++arr[index]: arr[index]=1;
        }
        
        for(let c of str){
          let index = c.charCodeAt(0) - 97;
          if(arr[index] == 1){
            return c;
          };
        }
    
        return -1;
    }("aabcbd"));
    
    console.log(firstUniqChar);

提交回复
热议问题