首页 > 代码库 > 383. Ransom Note

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


第二个字符串包含第一个字符串的所有字母,就返回true,不一定要连续包含
只要第一个字符串中某个字母的数量 大于 第二个字符串的这个字母的数量 则返回false

C++(19ms):

 1 class Solution {
 2 public:
 3     bool canConstruct(string ransomNote, string magazine) {
 4         vector<int> magazLetters(128, 0);
 5         for(char m : magazine)
 6             magazLetters[m]++;
 7         for(char r : ransomNote)
 8             if(--magazLetters[r]<0) return false;
 9         return true;
10     }
11 };

 

383. Ransom Note