HackerRank-Hash Tables: Ransom Note

Hash Tables: Ransom Note

A kidnapper wrote a ransom note but is worried it will be traced back to him. 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 whole words available in the magazine, meaning 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.

Input Format

The first line contains two space-separated integers describing the respective values of (the number of words in the magazine) and (the number of words in the ransom note).
The second line contains space-separated strings denoting the words present in the magazine.
The third line contains space-separated strings denoting the words present in the ransom note.

Constraints

.
Each word consists of English alphabetic letters (i.e., to and to ).
The words in the note and magazine are case-sensitive.
Output Format

Print Yes if he can use the magazine to create an untraceable replica of his ransom note; otherwise, print No.

Sample Input 0

6 4
give me one grand today night
give one grand today
Sample Output 0

Yes
Sample Input 1

6 5
two times three is not four
two times two is four
Sample Output 1

No

题目大意:给出两个字符串,问第二个字符串能否由第一个字符串中的单词拼成?
解题思路:用字典进行判断

def ransom_note(magazine, ransom):
    d1={}
    for i in magazine:
        d1[i]=0
    for i in magazine:
        if d1[i]==0:
            d1[i]=1
        else:
            d1[i]=d1[i]+1
    d2={}
    for i in ransom:
        d2[i]=0
    for i in ransom:
        if d2[i]==0:
            d2[i]=1
        else:
            d2[i]=d2[i]+1
    flag=True
    for key in d2:
        if (not (key in d1)) or d2[key]>d1[key]:
            flag=False
            break
    return flag

m, n = map(int, input().strip().split(' '))
#print(m)
#print(n)
magazine = input().strip().split(' ')
ransom = input().strip().split(' ')
#print(magazine)
#print(ransom)
answer = ransom_note(magazine, ransom)
#print(answer)
if(answer):
    print("Yes")
else:
    print("No")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值