Two strings are called anagrams if they contain same set of characters but in different order. For example, “keep” and “peek“.
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class AllAnagrams {
private static Set anagrams;
public static Collection getAllAnagrams(String string) {
anagrams = new HashSet();
permutation("", string);
return anagrams;
}
public static void main(String[] args) {
Collection anagrams = getAllAnagrams("peek");
for (String a : anagrams)
System.out.println(a);
}
private static void permutation(String prefix, String suffix) {
int suffixLength = suffix.length();
if (suffixLength == 0) {
anagrams.add(prefix);
} else {
for (int i = 0; i < suffixLength; i++) {
permutation(prefix + suffix.charAt(i), suffix.substring(0, i) + suffix.substring(i + 1, suffixLength));
}
}
}
}
Would give the following result:
eepk
ekpe
kpee
keep
epke
eekp
peke
kepe
epek
ekep
peek
pkee
Java Code to determine if two strings are anagrams of each other:
import java.util.ArrayList;
import java.util.List;
public class AreAnagrams {
public static boolean areAnagrams(String a, String b) {
List word = new ArrayList();
for (int i = 0; i < b.toCharArray().length; i++) {
word.add(b.charAt(i));
}
boolean ok = true;
int i = 0;
while (ok && i < a.toCharArray().length) {
Character c = a.charAt(i);
if (!word.contains(c)) {
ok = false;
}
word.remove(c);
i++;
}
return ok;
}
public static void main(String[] args) {
System.out.println(areAnagrams("apple", "pleap"));
System.out.println(areAnagrams("neural", "unreal"));
System.out.println(areAnagrams("neurls", "unreal"));
System.out.println(areAnagrams("orchestra", "carthorse"));
System.out.println(areAnagrams("orange", "apple"));
System.out.println(areAnagrams("ape", "monkey"));
}
}