LeetCode_383. Ransom Note

383. Ransom Note:
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

题意理解:
赎金条问题,能否从杂志中找到赎金条中的字符。即给定两个字符串,判断其中一个字符串能否由另外一个字符串中的字符组成,字符不能重复使用。

解题思路:
先判断两字符串长度,若赎金条字符长度大于杂志字符长度,则判定false;再对排序后的两字符串进行字符串的逐个比较。占用额外空间较少。运行耗时(53ms)。

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        if (ransomNote.size()>magazine.size())
            return false;
        int i=0, j=0;
        sort(ransomNote.begin(), ransomNote.end());
        sort(magazine.begin(), magazine.end());
        while(i<ransomNote.size() && j<magazine.size())
        {
            if (magazine[j]==ransomNote[i])
            {
                ++i;
            }
            ++j;
        }
        if (i==ransomNote.size())
            return true;
        else
            return false;

    }
};

Top Solution:
利用unordered_map/vector先统计magazine中的字符,再比较ransomNote中相应字符的数量是否满足要求。
(运行时间49ms/53ms)

unordered_map 是C++11新特性,与map类似。都是存储key-value的值,可以通过key快速索引到value。不同的是unordered_map不会根据key的大小进行排序。
内部实现机理:
1.map:map内部实现了一个红黑树,该结构具有自动排序的功能,因此map内部的所有元素都是有序的,红黑树的每一个节点都代表着map的一个元素,因此,对于map进行的查找,删除,添加等一系列操作都相当于是对红黑树进行相应的操作,故红黑树的效率决定了map的效率。
2. unordered_map: unordered_map内部实现了一个哈希表,因此其元素的排列顺序是杂乱的,无序的。

以上定义reference:
http://blog.csdn.net/u012530451/article/details/53228098

version_2:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> map;
        for (int i=0; i<magazine.size(); i++)
            ++map[magazine[i]];
        for (int j=0; j<ransomNote.size(); j++)
        {
            if (--map[ransomNote[j]]<0)
                return false;
        }
        return true;
    }
};

version_3:

class Solution {
public:
    bool canConstruct(string randomNote, string magazine) {
        vector<int> num(26, 0);
        for (int i=0; i<magazine.size(); i++)
            ++num[magazine[i]-'a'];
        for (int j=0; j<ransomNote.size(); j++)
        {
            if (--num[ransomNote[j]]<0)
                return false;
        }
        return true;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值