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
Test instructions: The topic is called ransom Note, blackmail letter, at the beginning I did not understand the meaning of the topic, especially the title, and magazine what is the relationship? Then think carefully, just slowly understand. Extortion letters, in order not to expose the handwriting, from the magazine search for the letters needed to form words to express the meaning. In this way, the title is clear, judging whether the word in the magazine can form the characters required for the ransom letter.
The thing to note here is that the characters in the magazine can only be used once, but the case is not a concern.
One of the simplest understandings is that the number of occurrences of each character in a ransomnote must be less than or equal to the number of times the character appears in magazine.
Original: http://blog.csdn.net/styshoo/article/details/52232993
Public class solution { public boolean canconstruct (String ransomnote, string magazine) { int[] hash1=new int[26]; int[] hash2=new int[26]; for (Int i=0;i<ransomnote.length (); i++) { hash1[ransomnote.charat (i)-' a ' +0]++; } for (int i=0;i< Magazine.length (); i++) { hash2[ Magazine.charat (i)-' a ']++; } for (int i=0;i<26;i++) { if (Hash1[i]>hash2[i]) return false; else continue; } return true; }}
PS: Used HashMap. Traverse letters and magazines, respectively, to get the number of letters that appear. If the number of magazines corresponds to less than the letter, false. The following is the leetcode on the fire? The principle is similar. is code simplification!!!
public boolean canconstruct (String ransomnote, string magazine) { int[] arr = new int[26]; for (int i = 0; i < magazine.length (); i++) { arr[magazine.charat (i) - ' a ']++; } for (Int i = 0; i < ransomnote.length (); i++) { if (--arr[ransomnote.charat (i)-' a '] < 0) { return false; } } return true; }
Leetcode 383. Ransom Note Java language