[LeetCode] First Letter to Appear Twice

아르당·2026년 8월 31일

LeetCode

목록 보기
499/584
post-thumbnail

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

Problem

영어 소문자로 구성된 문자열 s가 주어지고, 처음으로 2번 나타나는 문자를 반환해라.

Example

#1
Input: s = "abccbaacz"
Output: "c"

#2
Input: s = "abcdd"
Output: "d"

Constraints

  • 2 <= s.length <= 100
  • s는 영어 소문자로 구성된다.
  • s는 최소 한 번 반복하는 문자를 가진다.

Solved

class Solution {
    public char repeatedCharacter(String s) {
        Set<Character> hs = new HashSet<>();
        char result = 'a';

        for(int i = 0; i < s.length(); i++){
            if(hs.contains(s.charAt(i))){
                result = s.charAt(i);
                break;
            }

            hs.add(s.charAt(i));
        }

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

0개의 댓글