-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagram
More file actions
42 lines (33 loc) · 1.15 KB
/
anagram
File metadata and controls
42 lines (33 loc) · 1.15 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
/*
Two strings are called anagrams if they contain all the same characters in the same frequencies.
Constraints: The comparison should NOT be case sensitive.
*/
import java.util.HashMap;
import java.util.Scanner;
public class Solution {
static boolean isAnagram(String a, String b) {
if (a.length()!=b.length()) return false;
a = a.toLowerCase();
b = b.toLowerCase();
HashMap <Character, Integer> m = new HashMap<>();
for (int i=0; i<a.length(); i++) {
char c = a.charAt(i);
if (!m.containsKey(c)) m.put(c, 1);
else m.put(c, m.get(c)+1);
}
for (int i=0; i<b.length(); i++) {
char c = b.charAt(i);
if (!m.containsKey(c) || m.get(c)==0) return false;
else m.put(c, m.get(c)-1);
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
sc.close();
boolean rv = isAnagram(a, b);
System.out.println( rv ? "Anagrams" : "Not Anagrams" );
}
}