https://leetcode.com/problems/ransom-note/description/?envType=study-plan-v2&envId=top-interview-150
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
1.아이디어
magazine 문자열의 각 요소를 한 번 씩 사용하여 ransomNote의 문자열을 만들 수 있는지 확인하기 위해서
HashMap에 magazine에 존재하는 요소의 수를 기록해서 저장해 두었습니다.
그리고 for문을 사용해서 ransomNote의 각 요소가 맵에 존재하는지 확인하고 존재한다면 키 값에 해당하는 요소를 -1
하고 찾지 못했다면 false를 리턴합니다.
count변수를 이용하여 문자를 찾을 때마다 1씩 증가시키면서 count가 ransomNote의 length와 같다면 모든 문자를 찾았기 때문에 true를 리턴합니다.
2. 소스코드
import java.util.HashMap;
import java.util.Map;
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> map = new HashMap<>();
int count = 0;
for(char c : magazine.toCharArray())
{
map.put(c, map.getOrDefault(c,0) + 1);
}
for(int i = 0; i < ransomNote.length(); i++)
{
if(map.get(ransomNote.charAt(i)) == null)
return false;
if(map.get(ransomNote.charAt(i)) < 1 )
return false;
else
{
map.put(ransomNote.charAt(i), map.get(ransomNote.charAt(i)) - 1 );
count++;
}
}
if(count == ransomNote.length())
return true;
else
{
return false;
}
}
}
'ALGORITHM > 릿코드' 카테고리의 다른 글
LeetCode 234 Palindrome Linked List (1) | 2024.01.04 |
---|---|
릿코드 1.TWO SUM (0) | 2024.01.03 |
102. Binary Tree Level Order Traversal (0) | 2023.11.02 |
169. Majority Element (0) | 2023.11.02 |
88. Merge Sorted Array (0) | 2023.11.01 |