LeetCode 383. 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
解法一
思路
既然是要检查note中的字母是不是全都出现在magazines中,那不妨先遍历magazines一遍,记录下所有字母的出现次数,然后再遍历note,对每个字母检查其是否出现在magazines中,若出现则再检查出现次数是否比magazines中少。
在代码中有几个可以优化的地方:
- 记录magazines中字母出现次数一般用Map,但注意这里magazines中一定是小写字母,所以不妨用一个
int[26]
来存储。判断“字母是否存在”也只需要检查其值是否为0
即可。 - 检查出现次数时,对每个note中的字母,只需要将
int[]
中对应位置上的值减一就好了。当遇到int[]
中对应位置值为0时,只可能是字母在magazines中不存在,或字母在note中出现次数已经超过magazines中出现次数,这两种情况对应都是不满足题目要求的情况,直接返回False
就好了。
Python
class Solution:
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
has = [0] * 26
for item in magazine:
has[ord(item) - ord('a')] += 1
for item in ransomNote:
if has[ord(item) - ord('a')] == 0:
return False
has[ord(item) - ord('a')] -= 1
return True
Java
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] has = new int[26];
for (char item : magazine.toCharArray()) {
has[item - 'a']++;
}
for (char item : ransomNote.toCharArray()) {
if (has[item - 'a'] == 0) {
return false;
}
has[item - 'a']--;
}
return true;
}
}
C++
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> has(26, 0);
for (char item : magazine) {
has[item - 'a']++;
}
for (char item : ransomNote) {
if (has[item - 'a'] == 0) {
return false;
}
has[item - 'a']--;
}
return true;
}
};