[LeetCode] First Unique Character in a String

아르당·2026년 1월 7일

LeetCode

목록 보기
80/94
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 s가 주어졌을 때, 문자열에서 처음 반복되지 않는 문자를 찾아 해당 인덱스를 반환해라. 해당 문자가 존재하지 않으면 -1을 반환해라.

Example

#1
Input: s = "leetcode"
Output: 0
Explanation:
인덱스 0에 있는 문자 'l'은 다른 어떤 인덱스에도 나타나지 않는 첫 번째 문자이다.

#2
Input: s = "loveleetcode"
Output: 2

#3
Input: s = "aabb"
Output: -1

Constraints

  • 1 <= s.length <= 10^5
  • s는 영어 소문자로만 구성된다.

Solved

class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> freq = new HashMap<>();

        for(char c : s.toCharArray()){
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }

        for(int i = 0; i < s.length(); i++){
            if(freq.get(s.charAt(i)) == 1){
                return i;
            }
        }

        return -1;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글