In the following code I am finding all possible permutation of a given input string and storing them in a list and then counting the palindromes among them.This is working fine while the input String length is less than 10. But when input String length is larger than 10 it is taking a lot of time to finding permutations. I want to know what can be optimized here to get constant time for execution?
private static char[] inputArray;
private static List<String> listOfpermutations = new ArrayList<>();
private static int count;
public static void main(String s[]) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
inputArray = input.toCharArray();
permutation(0);
for (String combination : listOfpermutations) {
if (combination.equals(new StringBuilder(combination).reverse().toString())) {
count++;
}
}
System.out.println(count);
}
public static void permutation(int start)
{
String temp = "";
if (start != 0) {
if (start == inputArray.length) {
for (int i = 0; i < start; i++) {
temp = temp + inputArray[i];
}
if (!listOfpermutations.contains(temp)) {
listOfpermutations.add(temp);
}
}
}
for (int i = start; i < inputArray.length; i++)
{
swap(start, i);
permutation(start + 1);
swap(start, i);
}
}
static void swap(int pos1, int pos2) {
char temp = inputArray[pos1];
inputArray[pos1] = inputArray[pos2];
inputArray[pos2] = temp;
}
Tested Input:
- aaabbb //works awesome
- ccccddddcc //works fine
- ccccddddcce //here its taking too long