return the first non repeating character in a string in javascript

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

提交回复
热议问题