您的位置:首页 > 编程语言 > C语言/C++

<LeetCode OJ> 383. Ransom Note

2016-08-11 23:36 435 查看
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


分析:DONE

判断给定字符串Ransom 能否由另一字符串magazine中字符中的某些字符组合生成。

显然,统计字符出现次数即可!

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> charcnt(26,0);
//统计magazine中每个字符出现次数
for(int i=0;i<magazine.size();i++)
charcnt[magazine[i]-'a']++;
//统计ransomNote中每个字符出现次数
for(int i=0;i<ransomNote.size();i++)
charcnt[ransomNote[i]-'a']--;
//检查是否ransomNote中的数量是否都小于magazine中的!
for(int i=0;i<ransomNote.size();i++)
if(charcnt[ransomNote[i]-'a'] < 0)
return false;
return true;
}
};


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/52187660

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息