return the first non repeating character in a string in javascript

后端 未结 26 2212
清酒与你
清酒与你 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:24

    function firstUniqChar(str) {
        let myMap = new Map();
        for(let i = 0; i < str.length; i++) {
            let char = str.charAt(i);
            if(!myMap.has(char)) {
                myMap.set(char, 0);
            }
            myMap.set(char, myMap.get(char) + 1 );
        }
        for(let [key, value] of myMap) {
           if(value === 1) {
               return key;
           }
        }
        return null;
    }
    
    let result = firstUniqChar("caabbdccee");
    console.log(result);

    You can use Map Object and set key and value, where in value you store the count for that particular character, After that you can iterate over map and check where is value 1 and return that key.

    Map Object remembers the original insertion order of the keys.

    0 讨论(0)
  • 2020-12-30 09:25

    We can keep track of frequency of each character of the string in an object. For example : for "aabcbd" we can store the frequency as

    { "a":2, "b":2, "c":1, "d":1 }

    This will take O(n) time. Then we can traverse over this object and find the first character with frequency 1, which will also take O(n) time. So, the time complexity for this approach will be O(n).

    const firstNonRepeating=(str)=>{
    const obj={};
    str.split("").forEach(item=>{
      obj[item] 
      ? obj[item]++ 
      : obj[item]=1;
    });
    const item = Object.keys(obj).find(key=> obj[key] === 1);
    return item;
    }
    

    Note: I use ES6 Object.keys method which may not work in older browsers.

    0 讨论(0)
  • 2020-12-30 09:27

    If you're looking for the first occurrence of a letter that only occurs once, I would use another data structure to keep track of how many times each letter has been seen. This would let you do it with an O(n) rather than an O(n2) solution, except that n in this case is the larger of the difference between the smallest and largest character code or the length of the string and so not directly comparable.

    Note: an earlier version of this used for-in - which in practice turns out to be incredibly slow. I've updated it to use the character codes as indexes to keep the look up as fast as possible. What we really need is a hash table but given the small values of N and the small, relative speed up, it's probably not worth it for this problem. In fact, you should prefer @Guffa's solution. I'm including mine only because I ended up learning a lot from it.

    function firstNonRepeatedCharacter(string) {
       var counts = {};
       var i, minCode = 999999, maxCode = -1;
       for (i = 0; i < string.length; ++i) {
            var letter = string.charAt(i);
            var letterCode = string.charCodeAt(i);
           if (letterCode < minCode) {
               minCode = letterCode;
           }
           if (letterCode > maxCode) {
               maxCode = letterCode;
           }
            var count = counts[letterCode];
            if (count) {
               count.count = count.count + 1;
            }
            else {
                counts[letterCode] = { letter: letter, count: 1, index: i };
            }
       }
    
        var smallestIndex = string.length;
        for (i = minCode; i <= maxCode; ++i) {
           var count = counts[i];
           if (count && count.count === 1 && count.index < smallestIndex) {
              smallestIndex = count.index;
           }
       }
    
        return smallestIndex < string.length ? string.charAt(smallestIndex) : '';
    }
    

    See fiddle at http://jsfiddle.net/b2dE4/

    Also a (slightly different than the comments) performance test at http://jsperf.com/24793051/2

    0 讨论(0)
  • 2020-12-30 09:30
    Here is my solution using forEach and convert the string into an array
    function firstNotRepeatingCharacter(s) {
        var strArr = s.split("");
        var found = "_";
        strArr.forEach(function(item, index) {
            if (strArr.indexOf(item) == index && strArr.indexOf(item, index + 1) == -1) {
                if (found === "_") {
                    found = item;
                }
            }
        })
    
        return found;
    }
    
    firstNotRepeatingCharacter("abacabad")
    
    0 讨论(0)
  • 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);

    0 讨论(0)
  • 2020-12-30 09:33

    Here is my solution which have time complexity of o(n)

    function getfirstNonRepeatingCharacterInAString(params) {
        let count = {};
        for (let i = 0; i < params.length; i++) {
            let count1 = 0;
            if (!count[params.charAt(i)]) {
                count[params.charAt(i)] = count1 + 1;
            }
            else {
                count[params.charAt(i)] = count[params.charAt(i)] + 1;
            }
        }
        for (let key in count) {
            if (count[key] === 1) {
                return key;
            }
        }
        return null;
    }
    console.log(getfirstNonRepeatingCharacterInAString("GeeksfoGeeks"));
    
    0 讨论(0)
提交回复
热议问题