[LeetCode] Find the Difference

아르당·2026년 1월 8일

LeetCode

목록 보기
81/94
post-thumbnail

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

Problem

두 개의 문자열 s와 t를 갖게 된다.
문자열 t는 문자열 s를 무작위로 섞은 후 임의의 위치에 문자 하나를 추가하여 생성된다.

t에 추가된 문자를 반환한다.

Example

#1
Input: s = "abcd", t = "abcde"
Output: "e"
Explanation: 'e'는 추가된 글자이다.

#2
Input: s = "", t = "y"
Output: "y"

Constraints

  • 0 <= s.length <= 1000
  • t.length == s.length + 1
  • s와 t는 영어 소문자로 구성된다.

Solved

class Solution {
    public char findTheDifference(String s, String t) {
        Map<Character, Integer> count = new HashMap<>();

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

        for(char c : s.toCharArray()){
            count.put(c, count.get(c) - 1);

            if(count.get(c) == 0){
                count.remove(c);
            }
        }

        return (char) count.keySet().toArray()[0];
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글