Topic
Given? An? arbitrary? Ransom? Note? String another? containing? Letters from? All magazines? Write a? function? That would return? True if? Ransom? Note: Can constructed? from the magazines; otherwise,? It--it'll return false. ??
Each letter? In? The? Magazine? string? can? Only is? Used? Once? In? Your? Ransom? Note.
You may assume this both strings contain only lowercase letters.
Canconstruct ("A", "B")-Falsecanconstruct ("AA", "AB"), falsecanconstruct ("AA", "AaB"), True
[Topic parsing] First explicitly test instructions, two strings, the first letter in the string is obtained from the second string. You can use HashMap to read the first string into Hashmap,key is a character, and value is the number of characters that should be.
The second string is then traversed, the hashmap is manipulated, and the number of characters in the HashMap is sequentially--if the number is <0, then the characters contained in the map (that is, the first character) are not overwritten in the second string. The code is as follows.
Public Booleancanconstruct (String ransomnote, String magazine) {Map Charmap=NewHashmap<character,integer>(); for(intindex = 0; Index < Magazine.length (); index++){ CharTMP =Magazine.charat (index); if(Charmap.containskey (tmp)) {intCount = (int) Charmap.get (TMP); Count++; Charmap.put (TMP, Count); }Else{charmap.put (tmp,1); } } for(intindex = 0; Index < Ransomnote.length (); index++){ CharTMP =Ransomnote.charat (index); if(Charmap.containskey (tmp)) {intCount = (int) Charmap.get (TMP); Count--; if(Count < 0)return false; Charmap.put (TMP, Count); }Else{ return false; } } return true;}
Considering that there are only lowercase letters in the string, we can optimize the code and the whole idea is unchanged. The code is as follows.
Public Booleancanconstruct (String ransomnote, String magazine) {int[] arr =New int[26]; for(inti = 0; I < magazine.length (); i++) {Arr[magazine.charat (i)-' A ']++; } for(inti = 0; I < ransomnote.length (); i++) { if(--arr[ransomnote.charat (i)-' a '] < 0) { return false; } } return true; }
[Leetcode] no.383 Ransom Note