LeetCode: 383 Ransom Note(easy)

题目:

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

 

posted on 2017-09-11 20:55  玲珑子  阅读(82)  评论(0编辑  收藏  举报

导航