I am trying to find all possible string anagrams in Java. By this I mean that if I have a long word with a length of 4 characters, I want all possible 3 character long words to be derived from it, all two characters long and all 1 character long. The easiest way is to use two nested loops and iterate over the line. This is my code at the moment:
private ArrayList<String> subsets(String word){
ArrayList<String> s = new ArrayList<String>();
int length = word.length();
for (int c=0; c<length; c++){
for (int i=0; i<length-c; i++){
String sub = word.substring(c, c+i+1);
System.out.println(sub);
//if (!s.contains(sub) && sub!=null)
s.add(sub);
}
}
//java.util.Collections.sort(s, new MyComparator());
//System.out.println(s.toString());
return s;
}
My problem is that it works for three letter words, funsets this result (do not pay attention to ordering, the word is processed so that I have a line with letters in alphabetical order):
f
fn
fnu
n
nu
u
But when I try 4 letters, it leaves something, as in catqgives me:
a
ac
acq
acqt
c
cq
cqt
q
qt
t
i.e. 3 act - . , , , , , . - , , , . , .
: -, acq, qca, caq, aqc, cqa, qac .. - . , , , , acq. , , , , 4 , 3- , , - , .
, .