본문 바로가기

Algorithm

[LeetCode]First Unique Character in a String

문제 

Given a string sfind the first non-repeating character in it and return its index. If it does not exist, return -1.

주어진 문자열 s에서 반복되지 않는 첫번째 문자의 index를 반환하여라. 존재하지 않는다면, -1을 반환하라.

 

풀이 

/**
 * @param {string} s
 * @return {number}
 */
var firstUniqChar = function(s) {
    const array = Array.from(s);
    const countMap = new Map();
    
    for (let i = 0; i < array.length; i++) {
        countMap.set(array[i],{cnt : countMap.get(array[i]) ? countMap.get(array[i]).cnt + 1: 1, 
                               index: i});    
    } 
    
    for (let [key, value]  of countMap) {
        if (value.cnt === 1) {
            return value.index;
        }
    }
    
    return -1;
};

Runtime: 90 ms

Memory Usage: 51.1 MB

 

우선 string s를 배열로 바꾸어 준 뒤 각 단어의 반복 수와 index를 map에 담아주었다.

 

case : s = 'leetcode'

for-of로 map을 순회하며 cnt가 1인 key를 발견하면 해당 idex를 반환.

'Algorithm' 카테고리의 다른 글

[LeetCode] Find the Index of the First Occurrence in a String  (0) 2023.09.18
[LeetCode] Valid Palindrome  (0) 2023.09.14
[LeetCode] Reverse Integer  (0) 2023.09.14
[LeetCode] Move Zeroes  (0) 2023.09.13
[LeetCode] Count Primes  (0) 2023.09.13