Creating words from a set of words, character by character. Duplicates are allowed

Can anyone help with an efficient algorithm for such cases ?

Question: Given a list of words, find all the words which belong to this pattern

GIven:

{
"APPLE",
"ORANGE",
"BANANA",
"CARROT"
}

Words: AOBC, AOBA, AOBR. AOBR, AOBO, AOBT

An easy solution would be:

String[] elements = new String[]{
	"APPLE",
	"ORANGE",
	"BANANA",
	"CARROT"
}
final StringBuilder sb = new StringBuilder();
for(char a: elements[0].toCharArray()) {
	for(char b: elements[1].toCharArray()) {
		for(char c: elements[2].toCharArray()) {
			for(char d: elements[3].toCharArray()) {
				sb.append(a).append(b)..append(c).append(d).append(",");
			}
		}
	}
}
sb = sb.setLength(sb.length - 1);
Comments (0)