-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMapRansomNote.java
More file actions
67 lines (54 loc) · 1.71 KB
/
Copy pathHashMapRansomNote.java
File metadata and controls
67 lines (54 loc) · 1.71 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Input format
6 4 // number of words in magazine, number of words in ransomNote
give me one grand today night //Words present in magazine
give one grand today // Words present in ransomNote
Output: Gives true if all the words in ransomNote are in magazine, else false
*/
import java.util.*;
public class HashMapRansomNote {
Map<String, Integer> magazineMap;
private String magazine, note;
public HashMapRansomNote(String magazine, String note) {
this.magazine = magazine;
this.note = note;
magazineMap = new HashMap<String, Integer>();
}
public boolean solve(){
Integer i=0;
boolean isValid = true;
for(String word : magazine.split(" ")){
i = magazineMap.get(word);
if(i==null){
magazineMap.put(word,1);
}
else{
magazineMap.put(word,i+1);
}
}
for(String word1 : note.split(" ")){
i = magazineMap.get(word1);
if(i==null || magazineMap.get(word1)==0){
isValid = false;
break;
}
else{
magazineMap.put(word1, i-1);
}
}
return isValid;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
// Eat whitespace to beginning of next line
scanner.nextLine();
HashMapRansomNote s = new HashMapRansomNote(scanner.nextLine(), scanner.nextLine());
scanner.close();
boolean answer = s.solve();
if(answer)
System.out.println("Yes");
else System.out.println("No");
}
}