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

[LeetCode] Ransom Note

时间:2017-07-15 16:53:29      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:style   字母   turn   rar   use   ++   使用   can   ret   

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

 寻找ransomNote中的字母是否由magazine中的字母组成,且每一个在magazine中的字母在ransomNote中只能被使用1次。通过map建立magazine中字母与出现次数的查找表,遍历ransomNote,如果在map中找到该字母,则让map中的该字母出现的次数-1,若次数小于0,返回false;如果map中未找到这个字母,返回false。如果遍历结束仍没有返回值,说明ransomNote中的字母都是由magazine中的字母组成,返回true。

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> m;
        for (int i = 0; i != magazine.size(); i++)
            m[magazine[i]]++;
        for (int i = 0; i != ransomNote.size(); i++) {
            if (m.count(ransomNote[i])) {
                m[ransomNote[i]]--;
                if (m[ransomNote[i]] < 0)
                    return false;
            }
            else
                return false;
        }
        return true;
    }
};
// 36 ms

 

[LeetCode] Ransom Note

标签:style   字母   turn   rar   use   ++   使用   can   ret   

原文地址:http://www.cnblogs.com/immjc/p/7183227.html

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