LeetCode -- Ransom Note

来源:互联网 发布:ubuntu启动mysql服务 编辑:程序博客网 时间:2024/05/21 14:09
题目描述:

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


就是输入两个字符串,判断ransom是否为magazine的子集。
考查的是哈希表,hash[字符,出现次数]先遍历magazine递增次数,再遍历ransom递减次数,如果:
hash[ransomNote[i]]没有包含返回false;
hash[ransomNote[i]]为负数,返回false。

实现代码:

public class Solution {    public bool CanConstruct(string ransomNote, string magazine) {        var hash = new Dictionary<char,int>();for(var i = 0;i < magazine.Length; i++){            if(!hash.ContainsKey(magazine[i])){                hash.Add(magazine[i],1);            }            else{                hash[magazine[i]]++;            }        }        for(var i = 0;i < ransomNote.Length; i++){            if(!hash.ContainsKey(ransomNote[i])){return false;            }            else{                hash[ransomNote[i]] --;            }        }                        foreach(var k in hash.Keys){            if(hash[k] < 0){                return false;            }        }                return true;    }}


1 0
原创粉丝点击