privatebooleanpermute(int d, int n, StringBuilder sb) { if (d == n) { return testPalindromicity(sb); } for (inti= d; i < n; ++i) { swap(sb, d, i); if (permute(d + 1, n, sb)) returntrue; swap(sb, d, i); } returnfalse; }
// swap characters in a StringBuilder privatevoidswap(StringBuilder sb, int i, int j) { chartemp= sb.charAt(i); sb.setCharAt(i, sb.charAt(j)); sb.setCharAt(j, temp); }
privatebooleantestPalindromicity(StringBuilder sb) { intn= sb.length(); for (inti=0; i < n / 2; ++i) { if (sb.charAt(i) != sb.charAt(n - i - 1)) returnfalse; } returntrue; }
Time: $O(N \times N!)$ Space: $O(N)$
Hash Map
We can use hash map based on the fact that odd number of occurrences of a specific character can only occur once at most.
Actually, since there are only 128 ASCII characters, we can use an array of size 128 to store occurrences.