383. Ransom Note, 자바 풀이

이원석·2023년 9월 1일

Leetcode

목록 보기
14/22

[문제]
Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

https://leetcode.com/problems/ransom-note/?envType=study-plan-v2&envId=top-interview-150


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

        int cnt = 0;
        char[] ransC = ransomNote.toCharArray();
        char[] magC = magazine.toCharArray();

        for (char c : magC) {
            if (map.get(c) == null) {
                map.put(c, 1);
            } else {
                map.put(c, map.get(c) + 1);
            }
        }

        for (char c : ransC) {
            if (map.get(c) == null || map.get(c) <= 0) {
                return false;
            }

            if (map.get(c) > 0) {
                cnt += 1;
                map.put(c, map.get(c) - 1);
            }
        }

        if (cnt == ransomNote.length()) {
            return true;
        } else {
            return false;
        }
    }
}

// 주어진 ransomNote의 문자열의 요소들이 magazine에 포함되는지를 구분하는 문제이다.
// HashMap을 사용하여 해결해보자.
// 1. ransomNote, magazine 의 문자열을 문자형 배열로 변환시킨다.
// 2. magazine의 문자들을 HashMap의 key값으로 추가한다. (없을 경우 value=1, 있을 경우 value+=1)
// 3. ransomNote의 문자들을 key값으로 HashMap에서 찾아온다.
// 3-0. 만약 value가 map에 없는겨웅 return false;
// 3-1. 만약 value가 1 이상인 경우 cnt += 1, value -= 1
// 3-2. 만약 value가 0 이하인경우 return false;

0개의 댓글