leetcode 383. Ransom Note


Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can 
be 
constructed 
from 
the 
magazines ; 
otherwise, 
it 
will 
return 
false. 



Each 
letter
 in
 the
 magazine 
string 
can
 only 
be
 used 
once
 in
 your 
ransom
 note.

Note:
You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

 1 class Solution {
 2 public:
 3     bool canConstruct(string ransomNote, string magazine) {
 4         map<char,int> mpr,mpm;
 5         map<char,int>::iterator itr,itm;
 6         int i ,j;
 7         for(i=0; i < ransomNote.length();++i)
 8         {
 9             mpr[ransomNote[i]]++;
10         }
11         for(j = 0; j<magazine.length();++j)
12         {
13             mpm[magazine[j]]++;
14         }
15         if(mpr.size() > mpm.size()) return false;
16         itr = mpr.begin();itm = mpm.begin();
17         while(itr != mpr.end() && itm != mpm.end())
18         {
19             char tmp = itr->first;
20             map<char,int>::iterator t;
21         
22             if(mpm.find(tmp) == mpm.end())
23                 return false;
24 
25             if((int)(itr->second) > (int)(mpm.find(tmp)->second))
26                 return false;
27             else
28                 itr++;
29         }
30         return true;
31  
32     }
33 };

 

posted @ 2016-09-11 11:06  sunalive  Views(190)  Comments(0)    收藏  举报