LeetCode第一周总结

时间:2019-09-15
本文章向大家介绍LeetCode第一周总结,主要包括LeetCode第一周总结使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

LeetCode 383. Ransom Note

https://leetcode.com/problems/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

解法:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        vector<int> num(26);
        for(int i = 0; i < magazine.size(); i++)## 遍历 magazine,巧妙利用数组下标
            num[magazine[i] - 'a']++;
        for(int i = 0; i < ransomNote.size(); i++){
            num[ransomNote[i] - 'a']--;
            if(num[ransomNote[i]- 'a'] < 0)## 出现负数则返回false
                return false;
        }
            return true; 
    }
};

原文地址:https://www.cnblogs.com/dingxi/p/11523517.html