return the first non repeating character in a string in javascript

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

提交回复
热议问题