[LeetCode-383] Ransom Note (Java)

Source: Internet
Author: User

Given An arbitrary ransom note string and another string containing letters to all magazines, write 
A function that would return true if the ransom note can is constructed from the magazines; 

 Otherwise, it would return false.
The magazine string can only used once in your ransom.
You may assume this both strings contain only lowercase letters.
Canconstruct ("A", "B")-> false
Canconstruct ("AA", "AB")-> false
Canconstruct ("AA", "AaB")-> tru E
:
now gives the string str1 and str2 to determine whether str1 can be composed of characters in str2, only once in the str2, assuming that only lowercase letters are in the string.
Analysis:
A more intuitive way of thinking is: Directly traverse str1 and str2 the number of occurrences of each character, if a character in the str1 more than str2, obviously can not;
The number of a-Z in the string is stored in two arrays, then the value in the two array is compared, and false if the former is greater than the latter, otherwise returns true.

public class Solution {public boolean canconstruct (String Ransomnote, String magazine) {
        Only lowercase letters stating that the number of occurrences of 26 letters in the 2-string sequence int [] a=new int[26];
        int [] b=new int[26]; A[] Iterates over the number of occurrences of 26 letters in the ransomnote for (int i=0;i<ransomnote.length (); i++) {A[ransomnote.charat (i)-' a ']+
        +; //b[] traverses the number of occurrences of 26 letters in the magazine for (int j=0;j<magazine.length (); j + +) {B[magazine.charat (j)-'
        A ']++; //Loop compares the number of occurrences of 26 letters in 2 strings, and returns false for (int k=0;k<26;k++) {if (a[k) if the number of occurrences of a letter in array A is greater than the number of corresponding letters in B
        >b[k]) return false;
    return true; }
}

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.