题目地址
https://leetcode.com/problems/ransom-note/description/
题目描述
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.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraints:
You may assume that both strings contain only lowercase letters.
思路
- 用一个count数组.
- 第一遍遍历magazine的内容记录每个字符出现的个数.
- 第二遍遍历ansomNote的内容减去相应字符的个数, 若出现某个字符的个数小于0, 则返回false.
关键点
代码
- 语言支持:Java
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if (ransomNote == null || magazine == null) {
return false;
}
int[] map = new int[26];
for (int i = 0; i < magazine.length(); i++) {
int index = magazine.charAt(i) - 'a';
map[index]++;
}
for (int i = 0; i < ransomNote.length(); i++) {
int index = ransomNote.charAt(i) - 'a';
map[index]--;
if (map[index] < 0) {
return false;
}
}
return true;
}
}
// hashmap
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> map = new HashMap<>();
for (char c: magazine.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
for (char c: ransomNote.toCharArray()) {
if (!map.containsKey(c)) {
return false;
}
if (map.get(c) == 0) {
return false;
}
map.put(c, map.get(c) - 1);
}
return true;
}
}
网友评论