본문 바로가기

IN DEPTH CAKE/Supercoder

[c++/LeetCode-Hash Table] 387. First Unique Character in a String

 

 

 

 

 

난이도Easy

키워드: Stack

 

 

 

문자열 s가 주어졌을 때, 첫 번째로 반복되지 않는 문자를 찾고 그 인덱스를 반환합니다. 만약 그런 문자가 없다면, -1을 반환합니다.

 

입출력 예시

 

Example 1:

Input: s = "leetcode"
Output: 0

 

Example 2:

Input: s = "loveleetcode"
Output: 2

 

 

Example 3:

Input: s = "aabb"
Output: -1

 

class Solution {
public:
    int firstUniqChar(string s) {

        unordered_map<char, int> hash;

        for(const auto c : s){
            const auto ptr = hash.find(c);
            // first find
            if(ptr == hash.end())
                hash.insert({c, 1});
            // already found
            else
                ptr -> second += 1;
        }

        for(auto idx = 0; idx < s.size(); ++idx){
            if(hash.find(s[idx]) -> second == 1)
                return idx;
        }
        return -1;
    }
};

 

 

반응형