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.youkuaiyun.com/ebowtang/article/details/52187660
原作者博客:http://blog.youkuaiyun.com/ebowtang
本博客LeetCode题解索引:http://blog.youkuaiyun.com/ebowtang/article/details/50668895
本文介绍了一种算法,用于判断给定的勒索信字符串是否能通过另一个包含多个字母的字符串(如杂志内容)中的字符组合而成。文章提供了一个具体的C++实现方案,并详细解释了如何统计和比较两个字符串中字符的出现频率。
785

被折叠的 条评论
为什么被折叠?



