Ransom Note

来源:互联网 发布:免费微信多开软件 编辑:程序博客网 时间:2024/06/05 14:13

一、问题描述


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") -> falsecanConstruct("aa", "ab") -> falsecanConstruct("aa", "aab") -> true

二、思路

给定两个字符串,从其中一个中如果能够找到另一个字符串,返回真,否则返回假。

三、代码

class Solution {public:    bool canConstruct(string ransomNote, string magazine) {        if(ransomNote.size() > magazine.size()) return false;        int hash1[256] = {0},hash2[256] = {0};        for(int i = 0; i < ransomNote.size();++i)            hash1[ransomNote[i]]++;        for(int i = 0; i < magazine.size();++i)            hash2[magazine[i]]++;        for(int i = 0; i < 256; ++i){            if(hash1[i] > hash2[i]) return false;        }        return true;    }};



0 0
原创粉丝点击