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.

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

代码:

 1 class Solution {
 2 public:
 3     bool canConstruct(string ransomNote, string magazine) {
 4         if (ransomNote == "")
 5             return true;
 6         for (auto c : ransomNote){
 7             int position = magazine.find_first_of(c); 
 8             if (position != magazine.npos)
 9                 magazine.erase(position, 1);
10             else
11                 return false;        
12         }
13        return true;    
14     }
15 };

别人的:

 1 class Solution {
 2 public:
 3     bool canConstruct(string ransomNote, string magazine) {
 4         int mp[26] = {0};
 5         for(auto c : magazine) {
 6             mp[c - 'a']++;
 7         }
 8         for(auto r : ransomNote) {
 9             mp[r - 'a']--;
10             if(mp[r - 'a'] < 0) return false;
11         }
12         return true;
13     }
14 };

 

相关文章:

  • 2022-12-23
  • 2022-02-13
  • 2022-01-08
  • 2021-09-29
  • 2021-12-19
  • 2022-12-23
  • 2021-11-12
  • 2021-05-17
猜你喜欢
  • 2022-02-19
  • 2022-12-23
  • 2021-08-14
  • 2021-09-20
  • 2021-07-03
相关资源
相似解决方案