What is anagram?
Any word or phrase that exactly reproduces the letters in another order is an anagram. (
Wikipedia)
Example of anagrams: DOG, GOD, DGO, GDO, OGD, ODG,
Task:
to determine whether two strings anagrams.
Solution:
1) make both strings similar case - use toLowesrCase() method
2) Convert each string to char array
3) Use HashMap - for each character in first char array calculate number of repeats. And after that for second char array for each character decrease count of repeats. So if two string are anagrams than we have to get hash map object where for each character we have zero value.
Source code:
import java.util.HashMap;
import java.util.*;
public class Main {
static boolean isAnagram(String a, String b) {
HashMap<Character, Integer> hash = new HashMap();
char[] arr1 = a.toLowerCase().toCharArray();
char[] arr2 = b.toLowerCase().toCharArray();
for (char c : arr1) {
int count = 1;
if (hash.containsKey(c)) {
count = hash.get(c) + 1;
}
hash.put(c, count);
}
for (char c : arr2) {
int count = -1;
if (hash.containsKey(c)) {
count = hash.get(c) - 1;
}
hash.put(c, count);
}
for (char c : hash.keySet()) {
if (hash.get(c) != 0) {
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");
}
}
Results:
Test 1:
Hello
olleh
Anagrams
Test 2:
Hello
helll
Not Anagrams
Test 3:
Morning
gninromm
Not Anagrams
Test 4:
Programming
mmggrrpoain
Anagrams