넘치게 채우기

[LeetCode] 387. First Unique Character in a String 본문

PS/LeetCode

[LeetCode] 387. First Unique Character in a String

riveroverflow 2024. 2. 5. 10:58
728x90
반응형

https://leetcode.com/problems/first-unique-character-in-a-string/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Leetcode - First Unique Character in a String

문제 유형 : 문자열 처리, 해시

문제 난이도 : Easy

 

문제

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

문자열 s가 주어진다. 반복되지 않는 첫 문자의 인덱스를 반환하시오.

없으면 -1을 반환하시오.

 

풀이

해시맵의 key를 문자, value를 개수로 한다.

문자열을 하나씩 읽으면서 개수를 센다.

다시 배열의 처음부터 확인하면서, 단 한번 등장한 숫자의 인덱스를 반환한다.

없다면 -1을 반환하면 된다.

 

코드

C++

class Solution {
public:
    int firstUniqChar(string s) {
        const int n = s.size();
        unordered_map<int, int> mp;

        for(const auto &ch : s) {
            mp[ch]++;
        }

        for(int i = 0; i < n; i++) {
            if(mp[s[i]] == 1) return i;
        }
        return -1;
    }
};

 

Go

func firstUniqChar(s string) int {
    mp := map[rune]int {}

    for _, v := range s {
        mp[v]++;
    }

    for i, v := range s {
        if mp[v] == 1 {
            return i
        }
    }

    return -1
}
728x90
반응형