您的位置:首页 > 其它

383. Ransom Note

2017-03-25 19:37 295 查看

 

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: