383. Ransom Note

양성준·2025년 4월 29일

코딩테스트

목록 보기
35/102

문제

https://leetcode.com/problems/ransom-note/description/

풀이

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character, Integer> map = new HashMap<>();

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

        for(char c : magazine.toCharArray()) {
                map.put(c, map.getOrDefault(c,0) - 1);
        }

        for(int n : map.values()) {
            if(n > 0) {
                return false;
            }
        }

        return true;
        
    }
}
  • 쓰지 않는 문자열은 음수여도 상관없으므로 map.put(c, map.getOrDefault(c,0) - 1);
  • 중요한건 쓰는 문자열이 로직을 통과했을 때도 양수일 경우
profile
백엔드 개발자

0개의 댓글