1.문제
Ransom Note - LeetCode
Can you solve this real interview question? Ransom Note - 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 ranso
leetcode.com
2.문제설명
- ransomNote 를 가지고 magazine 을 만들 수 있으면 True 없으면 False

3.소스코드
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
HashMap<Character, Integer> cntMap = new HashMap<>();
for (char c : magazine.toCharArray()) {
cntMap.put(c, cntMap.getOrDefault(c, 0) + 1);
}
for (char c : ransomNote.toCharArray()) {
if (cntMap.containsKey(c) && cntMap.get(c) > 0) {
cntMap.put(c, cntMap.get(c) - 1);
} else {
return false;
}
}
return true;
}
}
4.소스코드 설명
ransomNote 에 해당되는 글자를 카운트 해주기 위해 HashMap 을 구성하고
체크해야할 magazine 을 순회 하면서 해당되는 글자를 카운트 증가를 시킵니다(cntMap.getOrDefault(c,0)+1 ) 만약 없다면 증가 시키는 구조를 만듭니다.
그 이후 ransome 에 포함하였는지 체크 하는 순환을 하고 존재한다면 감소합니다.
5.회고

이 문제를 풀면서 꼭 HashMap 이 속도 와 메모리에서 우수하다는것은 아니라는것을 알았다.
이런 문제에서는 직접 배열을 만들어 체크하는것이 속도와 메모리에서 우수한것을 확인하게 되었다.
'Algorithm' 카테고리의 다른 글
| [leetcode 208번] Implement Trie (Prefix Tree) (JAVA) (0) | 2023.09.11 |
|---|---|
| [leetCode 242번] Valid Anagram (Java) (0) | 2023.08.31 |
| [leetCode 219번] Contains Duplicate II (Java) (0) | 2023.08.31 |
| [leetCode 1번] Two Sum (Java) (0) | 2023.08.31 |
| [leetCode 155] Min Stack (Java) (0) | 2023.08.30 |