从零开始的LC刷题(79): 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

判断一个string里的所有字母是否全部来自另一个string(无视顺序),先把所有词库入map试水,结果:

Success

Runtime: 32 ms, faster than 45.58% of C++ online submissions for Ransom Note.

Memory Usage: 11 MB, less than 55.14% of C++ online submissions for Ransom Note.

代码:

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

修改一下代码把ransom入map就会快一点:

Success

Runtime: 24 ms, faster than 75.37% of C++ online submissions for Ransom Note.

Memory Usage: 11.1 MB, less than 45.81% of C++ online submissions for Ransom Note.

代码:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        if(!ransomNote.size()){return true;}
        map<char,int> lib;
        for(int i=ransomNote.size()-1;i>=0;i--){
            lib[ransomNote[i]]++;
        }
        map<char,int>::iterator it;
        for(int i=magazine.size()-1;i>=0;i--){
            it=lib.find(magazine[i]);
            if(it==lib.end()){continue;}
            if(lib[magazine[i]]>1){lib[magazine[i]]--;}
            else if(lib[magazine[i]]==1){lib.erase(magazine[i]);}
            if(!lib.size()){return true;}
        }
        return false;
    }
};

还是不够快,想不如试一下数组哈希好了,结果反而变好了:

Success

Runtime: 16 ms, faster than 97.44% of C++ online submissions for Ransom Note.

Memory Usage: 10.7 MB, less than 87.57% of C++ online submissions for Ransom Note.

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值