leetcode Ransom Note

leetcode 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

题目地址:leetcode Ransom Note

题目大意:给定两个字符串magazines和ransomNote,问是否可以从magazines中抽取字母(每个字母只能用一次)组成ransomNote

思路:只要判断ransomNote字符是不是全部在magazines中即可,用hash。。 水

C++

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        vector<int> cnt(26,0);
        for(char x:magazine) cnt[x-97]++;
        for(char x:ransomNote) if(--cnt[x-97] < 0) return false;
        return true;
    }
};

Java

public class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] cnt = new int[26];
        for (int i = 0; i < magazine.length(); i++) cnt[magazine.charAt(i) - 97]++;
		for (int i = 0; i < ransomNote.length(); i++) if (--cnt[ransomNote.charAt(i) - 97] < 0) return false;
		return true;
    }
}

Python

class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        cnt = collections.Counter(magazine)
        for letter in ransomNote:
            cnt[letter] -= 1
            if cnt[letter] <0: return False
        return True

 

 

本题是leetcode 383 Ransom Note 的题解

更多题解可以查看:https://www.hrwhisper.me/leetcode-algorithm-solution/

 

本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode Ransom Note
本文地址:https://www.hrwhisper.me/leetcode-ransom-note/

您的支持将鼓励我继续创作!

Leetcode , , , , . permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *