본문으로 바로가기

[LeetCode] 383. Ransom Note - 문제풀이

category 알고리즘/LeetCode 2022. 1. 24. 00:47

Description

주어진 magazine 배열이 ransomNote에 주어진 단어를 포함할 수 있는지 여부를 반환하는 문제입니다.

Given two strings ransomNote and magazine, return true if ransomNote can be constructed from magazine and false otherwise.

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

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

Constraints:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.

Solution 1. Hash Table

public boolean canConstruct(String ransomNote, String magazine) {

    int[] map = new int[26];
    for (int i = 0; i < magazine.length(); i++) {
        map[magazine.charAt(i)-'a']++;
    }

    for (int i = 0; i < ransomNote.length(); i++) {
        if(--map[ransomNote.charAt(i)-'a'] < 0){
            return false;
        }
    }
    return true;
}

소문자는 26자리기 때문에 각 문자를 인덱스로 가지는 배열을 맵으로 사용하여 문자별 카운트를 기록해 두고 ransomNote의 단어를 만들 수 없는 경우 (배열의 요소값이 음수 전환) false 반환하고 모든 문자열 검색을 다 통과했을 경우 true를 반환해 줍니다.

Reference

 

Ransom Note - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com