码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode第一周总结

时间:2019-09-15 19:39:42      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:problem   ini   lower   fun   only   you   const   总结   题目   

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; 
    }
};

 

LeetCode第一周总结

标签:problem   ini   lower   fun   only   you   const   总结   题目   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!