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; }
}