Hash Tables: Ransom Note

15987 단어 hackerrankhackerrank

🔗 문제 링크

https://www.hackerrank.com/challenges/ctci-ransom-note/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps


❔ 문제 설명


Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words available in the magazine. He cannot use substrings or concatenation to create the words he needs.

Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No.

Example

magazine = "attack at dawn" note = "Attack at dawn"

The magazine has all the right words, but there is a case mismatch. The answer is No.

Function Description

Complete the checkMagazine function in the editor below. It must print Yes if the note can be formed using the magazine, or No.

checkMagazine has the following parameters:

  • string magazine[m]: the words in the magazine
  • string note[n]: the words in the ransom note

Prints

  • string: either Yes or No, no return value is expected

Input Format

The first line contains two space-separated integers, m and n, the numbers of words in the magazine and the note, respectively.
The second line contains space-separated strings, each magazine[i].
The third line contains space-separated strings, each note[i].


⚠️ 제한사항


  • 1m,n300001 ≤ m, n ≤ 30000

  • 1len(magazine[i]),len(note[i])51 ≤ len(magazine[i]), len(note[i]) ≤ 5

  • Each word consists of English alphabetic letters (i.e., a to z and A to Z).



💡 풀이 (언어 : Java)


Hashtable을 사용해서 풀었다. 키값은 대소문자를 구별하기 때문에 별도의 대소문자 처리는 필요가 없었다. 디테일하게 고려한 점은 Hashtable에 value로 단어 수를 카운팅해서 넣어주었다. 같은 글자가 연속으로 필요할 때는 잡지에는 하나만 있는데, value로 단어 수를 차감해주지 않으면 note에서 여러번 등장해도 계속 사용가능한 것으로 판별되는 것을 고려해서 작성했다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Hashtable;

public class Main {
    private static String checkMagazine(String[] magazine, String[] note) {
        Hashtable<String, Integer> ht = new Hashtable<String, Integer>();
        for (String word : magazine) {
            if (!ht.containsKey(word)) {
                ht.put(word, 1);                
            } else {
                ht.replace(word, ht.get(word)+1);
            }
        }
        
        for (String word : note) {
            Integer num = ht.get(word);
            if (num == null || num < 1) {
                return "No";
            } else {
                ht.replace(word, num-1);
            }
        }
        return "Yes";
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        br.readLine();
        String[] magazine = br.readLine().split(" ");
        String[] note = br.readLine().split(" ");
        System.out.println(checkMagazine(magazine, note));
        br.close();
    }
}

좋은 웹페이지 즐겨찾기