LeetCode 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

思路:

统计两个字符串中各个字符的数量,如果第一个字符串中每个字符数量都小于第二个字符串对应字符的数量,则返回true;否则,返回false。

方法1. 使用两个map<char,int>分别统计每个字符串中每个字符的数量,然后判断第一个字符串中字符数量是否是否小于第二个字符串中对应字符的字符数量。

方法2. 使用一个map,首先遍历第一个字符串,统计每个字符数量;然后遍历第二个字符串,遇见对应字符,字符数量减1;最后遍历map,如果所有字符数量均大于0,则返回true,否则返回false。

Code1:

class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        map<string,int> comResM;
        vector<string> comRes;
        vector<string> :: iterator it;
        int l1,l2;
        int sum=list1.size()+list2.size();
        for(int i=0;i<list1.size();i++){
            it = find(list2.begin(),list2.end(),list1[i]);
            if(it!=list2.end()){
                l1=i;
                l2=distance(list2.begin(),it);
                comResM[list1[i]] = l1+l2;
                if((l1+l2)<sum) sum=l1+l2;
            }
        }
        for(auto & n:comResM){
            if(n.second==sum) comRes.push_back(n.first);
        }
        return comRes;
    }
};

Code2:

class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        unordered_map<string, int> hash1;
        for (int i = 0; i < list1.size(); i++) {
            hash1[list1[i]] = i;
        }
        unordered_map<int, vector<string> > ans;
        int min = 99999999;
        for (int j = 0; j < list2.size(); j++) {
            auto got = hash1.find(list2[j]);
            if (got != hash1.end()) {
                int common = got->second + j;
                if (common <= min) {
                    min = common;
                    ans[min].push_back(list2[j]);
                }
            }
        }
        return ans[min];
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值