In: Computer Science
Write a recursive method using Java that takes a string s as input and returns a list that contains all the anagrams of the string s. An anagram is a word formed by rearranging the letters of a different word. For instance, the word ‘cat’ is an anagram of ‘act’. Notice that the output list cannot contain duplicates.
import java.util.*;
//Created class anagram
public class Anagram {
//Adding hashset to remove all duplicates
HashSet<String> set=new HashSet();
//Recursion method for anagram
public HashSet<String> anag(String s1, String s2) {
if(s1.length() == 0) {
set.add(s2);
}
for(int i = 0; i < s1.length(); i++) {
anag(s1.substring(0, i) + s1.substring(i+1, s1.length()), s1.charAt(i) + s2);
}
return set;
}
public static void main(String[] args) {
//Object for class anagram
Anagram ana = new Anagram();
String word;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a word: ");
word=scan.nextLine();
System.out.println("The anagrams are: ");
HashSet<String> set=ana.anag(word, "");
//Iterator for hashset
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Sample input and output:
Enter a word: cat
The anagrams are:
atc
cta
tca
act
tac
cat
Enter a word: liril
The anagrams are:
lliri
lrili
rilil
rlili
ilrli
ililr
ilirl
illri
liril
lilir
irill
irlli
lriil
lrlii
liirl
riill
rilli
lilri
ilril
illir
rliil
iirll
rllii
iillr
lirli
liilr
llrii
lliir
irlil
iilrl