383. Ransom Note

来源:互联网 发布:淘宝小视频制作软件 编辑:程序博客网 时间:2024/05/22 14:51

原题链接:https://leetcode.com/problems/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

给出一个任意的字母串,以及另外一个字母串,判断第一个字母串里面的所有字母是不是第二个字母串里面所有字母的子集。
例:
canConstruct(“a”, “b”) -> false 不是子集
canConstruct(“aa”, “ab”) -> false 不是子集
canConstruct(“aa”, “aab”) -> true 是子集

直接统计两个字母串里面的所有字母出现的频率,然后比较每个字母出现的次数就可以了。

代码如下:

class Solution {public:    bool canConstruct(string ransomNote, string magazine) {        int ran[52] = {0};        int mag[52] = {0};        for(auto str : ransomNote) {            if(str >= 'a' && str <= 'z') ran[(str - 'a')] ++;            else ran[(str - 'A') + 26] ++;        }        for(auto str : magazine) {            if(str >= 'a' && str <= 'z') mag[(str - 'a')] ++;            else mag[(str - 'A') + 26] ++;        }        for (int i = 0; i < 52; ++i) {            if(ran[i] > mag[i]) return false;        }        return true;    }};
0 0
原创粉丝点击