[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.

1
2
3
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

解题思路与代码

给定两个字符串magazine和ransomNote,问ransomNote是否可以从magazine中抽取字母(每个字母只能用一次)组成。思路挺简单,只要判断ransomNote中的字符是否全部在magazine中即可,利用hash即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

public class {
public boolean canConstruct1(String ransomNote, String magazine) {

int[] map = new int[26];

// for(int i = 0; i < magazine.length(); i++){
// map[magazine.charAt(i) - 'a']++;
// }

// for(int i = 0; i < ransomNote.length(); i++){
// if(--map[ransomNote.charAt(i) - 'a'] < 0) return false;
// }

for(char ch : magazine.toCharArray()){
map[ch - 'a']++;
}

for(char ch : ransomNote.toCharArray()){
if(--map[ch - 'a'] < 0) return false;
}

return true;
}

public boolean canConstruct(String ransomNote, String magazine) {
//可以用HashMap<Character, Integer>
Map<Character, Integer> map = new HashMap<>();

for(char ch : magazine.toCharArray()){
if(map.containsKey(ch)){
map.put(ch, map.get(ch) + 1);
}else{
map.put(ch, 1);
}
}

for(char ch : ransomNote.toCharArray()){
if(map.containsKey(ch)){
int newCount = map.get(ch) - 1;
if(newCount < 0) return false;
map.put(ch, newCount);
}else{
return false;
}
}

return true;
}
}