leetcode383

1、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.
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
判断第一个字符串是否能由第二个字符串的某部分组成嗯~
就是保证第一个字符串的每一种字符的个数小于等于第二个字符串的,可以用删除法判断。第二种会快一点

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char,int> result;
        for(char i : magazine)
            result[i]++;// first=i的second++;
        for(char i : ransomNote){
            result[i]--;
            if(result[i] == -1)
                return false;
        }
        return true;
    }
};

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        int i = 0;
        int length = ransomNote.size();
        for(;i < length; i++){
            auto tem = find(magazine.begin(), magazine.end(), ransomNote[i]);
            if(tem == magazine.end())
                break;
            magazine.erase(tem);
        }
        if(i == length)
            return true;
        return false;
    }
};

1、for(char i : ransomNote)
等价于:

for(int a = 0; a < ransomNote.size(); a++)
    char i = ransomNote[a];

2、InputIterator find (InputIterator first, InputIterator last, const T& val);
若存在val,返回它的迭代器,不存在返回last。复杂度为O(n)。
3、string& erase ( size_t pos = 0, size_t n = npos );
iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值