-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAnagrams.java
More file actions
47 lines (43 loc) · 1.36 KB
/
Anagrams.java
File metadata and controls
47 lines (43 loc) · 1.36 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
import java.util.HashMap;
import java.util.Scanner;
public class Anagrams{
static boolean isAnagram(String a, String b) {
// Complete the function
if(a.length() != b.length() || a.equals("") || b.equals(""))
return false;
char index;
int freq;
HashMap<Character,Integer> letters = new HashMap<Character,Integer>();
a = a.toUpperCase();
b = b.toUpperCase();
for(int i = 0; i < a.length(); i++){
index = a.charAt(i);
if(letters.containsKey(index)){
freq = letters.get(index);
letters.replace(index, ++freq);
}
else
letters.put(index,1);
}
for(int i = 0; i < b.length(); i++){
index = b.charAt(i);
if(letters.containsKey(index)){
freq = letters.get(index);
if(freq == 0)
return false;
letters.replace(index, --freq);
}
else
return false;
}
return true;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String a = scan.next();
String b = scan.next();
scan.close();
boolean ret = isAnagram(a, b);
System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
}
}