码迷,mamicode.com
首页 > 其他好文 > 详细

<LeetCode OJ> 383. Ransom Note

时间:2016-08-12 01:29:13      阅读:463      评论:0      收藏:0      [点我收藏+]

标签:

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

分析:

判断给定字符串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

<LeetCode OJ> 383. Ransom Note

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!