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.
Note:
You may assume this both strings contain only lowercase letters.
Canconstruct ("A", "B")-Falsecanconstruct ("AA", "AB"), falsecanconstruct ("AA", "AaB"), True
Analysis:
Determines whether a given string ransom can be generated by a combination of some characters in a character in another string magazine.
Obviously, count the number of characters to appear!
Class Solution {public: bool Canconstruct (String Ransomnote, String magazine) { vector<int> charcnt (26,0 ); Count the occurrences of each character in the magazine for (int i=0;i<magazine.size (); i++) charcnt[magazine[i]-' a ']++; Count the occurrences of each character in the ransomnote for (int i=0;i<ransomnote.size (); i++) charcnt[ransomnote[i]-' a ']--; Check if the number in the Ransomnote is less than magazine! for (int i=0;i<ransomnote.size (); i++) if (charcnt[ransomnote[i]-' a '] < 0) return false; return true; }};
Note: This blog post is Ebowtang original and may continue to be updated later in this article. If reproduced, please make sure to copy this article information!
Original address: http://blog.csdn.net/ebowtang/article/details/52187660
Original Author Blog: Http://blog.csdn.net/ebowtang
This blog leetcode key index: http://blog.csdn.net/ebowtang/article/details/50668895
<leetcode oj> 383. Ransom Note