题目
给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。
(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。杂志字符串中的每个字符只能在赎金信字符串中使用一次。)
示例
输入:ransomNote = “a”, magazine = “b”
输出:false
输入:ransomNote = “aa”, magazine = “ab”
输出:false
输入:ransomNote = “aa”, magazine = “aab”
输出:true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ransom-note
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1
python实现:counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
c1=collections.Counter(ransomNote)
c2=collections.Counter(magazine)
for var in ransomNote:
if c1[var] != c2[var] and c1[var] > c2[var]:
return False
return True
Java实现1:数组队列模拟
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
List<Character> list = new ArrayList<>();
// 记录magazine的字母
for (Character ch : magazine.toCharArray()) {
list.add(ch);
}
for (Character ch : ransomNote.toCharArray()) {
if (!list.contains(ch)) {
return false;
}
list.remove(ch);
}
return true;
}
}
Java实现2:哈希表模拟
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < magazine.length(); i++) {
map.put(magazine.charAt(i), map.getOrDefault(magazine.charAt(i), 0) + 1);
}
for (int i = 0; i < ransomNote.length(); i++) {
if (!map.containsKey(ransomNote.charAt(i))) return false;
map.put(ransomNote.charAt(i), map.get(ransomNote.charAt(i)) - 1);
if (map.get(ransomNote.charAt(i)) == 0) map.remove(ransomNote.charAt(i));
}
return true;
}
}
Java实现3:数组模拟
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] res = new int[26];
for (char c : magazine.toCharArray()) res[c - 'a']++;
for (char c : ransomNote.toCharArray()) {
if (--res[c - 'a'] < 0) return false;
}
return true;
}
}