// Steps to rearrange the string:
// - define array with size 256 which contains frequency of char index.
// - define heap node with key of type char and its frequency of type int
// - create max heap as per frequency element heap node
// - Itreate till length of string
// remove max frequency node from heap
// place it at k = i + (f-1)*d positions of result string
static String rearrange(String str, int d) throws CustomException{
int n = str.length();
if(n == 0 || n == 1) return str;
char[] res = new char[n];
for(int i=0; i
res[i] = 0;
}
int[] arrf = new int[260];
heapnd[] hn = new heapnd[n];
for (int i = 0; i
arrf[str.charAt(i)] ++;
}
int j =0;
for(int i = 0; i<260 i="" p=""> {
if(arrf[i] != 0)
{
hn[j++] = new heapnd((char) i ,arrf[i]);
}
}
maxHeap(hn,j);
for(int i =0; i
if(res[i] != 0)
{
continue;
}
heapnd maxfreq = hn[0];
int k;
for(int l = 1; l<= maxfreq.freq; l++)
{
k = i + (l-1)*d;
if(k>n-1) throw new CustomException("Can't rearrange this string.");
res[k] = maxfreq.key;
}
if(j > 0)
{
hn[0] = hn[j-1];
j = j-1;
maxheapify(hn, 0, j);
}
}
return new String(res);
}
private static void maxHeap(heapnd[] hn, int n){
if(n == 0 || n == 1) return;
for(int i = (n-1)/2; i>=0; i--)
{
maxheapify(hn, i, n);
}
}
private static void maxheapify(heapnd[] hn, int i, int n) {
int l = left(i);
int r = right(i);
int maxIndex = i;
if(l
if(r
if(maxIndex != i)
{
swap(hn, i, maxIndex);
}
}
private static void swap(heapnd[] hn, int i, int maxIndex2) {
heapnd tmp = hn[i];
hn[i] = hn[maxIndex2];
hn[maxIndex2] = tmp;
}
class CustomException extends Exception{
private static final long serialVersionUID = 1L;
private String str;
public CustomException(String str)
{
this.str = str;
}
public String toString()
{
return str;
}
}
Reference:
http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/