首页 > 其他 > 详细

LeetCode第一周总结

时间:2019-09-15 17:57:40      阅读:75      评论:0      收藏:0      [点我收藏+]

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第一周总结

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!