[알고리즘] LeetCode - First Unique Character in a String

Jerry·2021년 1월 28일
0

LeetCode

목록 보기
22/73
post-thumbnail

LeetCode - First Unique Character in a String

문제 설명

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

Examples

s = "leetcode"
return 0.
s = "loveleetcode"
return 2.

Solution

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
  
    let mapIdx=new Map();

    for(let i=0; i<s.length; i++){
        let temp=mapIdx.get(s[i]);
        if(temp!=null){
            if(temp!=-1){
            mapIdx.set(s[i],-1)
            }
        }else{
            mapIdx.set(s[i],i);
        }
    }

    let mapValues = map.values();
    
    for(let val of mapValues){
        if(val!=-1){
            return val;
        }
    }
    return -1;
};

~.~

profile
제리하이웨이

0개의 댓글