Leetcode 383 Ransom Note

Source: Internet
Author: User

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that Would return true if the ransom note can be constructed from the magazines; Otherwise, it'll return false.

The magazine string can is used once in your ransom note.

Note:

You may assume this both strings contain only lowercase letters.

Canconstruct ("A", "B")-Falsecanconstruct ("AA", "AB"), falsecanconstruct ("AA", "AaB"), True

The more straightforward idea is to take the characters from the Ransomnote to the magazine, and if you find that a character doesn't exist in magazine, that means the answer is false.

1 defcanconstruct (Self, Ransomnote, magazine):2         """3 : Type Ransomnote:str4 : Type Magazine:str5 : Rtype:bool6         """7R =list (ransomnote)8m =List (magazine)9          forXinchr:Ten             ifXinchm: One m.remove (x) A             Else: -                 returnFalse -         returnTrue

Another way is to count the number of each letter in the two Str and subtract it. IfransomCnt - magazineCnt非空,那么答案就是False.

1 ransomcnt = collections. Counter (ransomnote)2 magazinecnt = collections. Counter (magazine)3return not ransomcnt-magazinecnt

Leetcode 383 Ransom Note

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.