Rearrange a string so that all same characters become d distance away minDistance priority queue

来源:互联网 发布:英伦对决影评知乎 编辑:程序博客网 时间:2024/05/01 01:08

Given a string and a positive integer d. Some characters may be repeated in the given string. Rearrange characters of the given string such that the same characters become d distance away from each other. Note that there can be many possible rearrangements, the output should be one of the possible rearrangements. If no such arrangement is possible, that should also be reported.
Expected time complexity is O(n) where n is length of input string.

**Examples:
Input: “abb”, d = 2
Output: “bab”
Input: “aacbbc”, d = 3
Output: “abcabc”
Input: “geeksforgeeks”, d = 3
Output: egkegkesfesor
Input: “aaa”, d = 2
Output: Cannot be rearranged**

Solution: The idea is to count frequencies of all characters and consider the most frequent character first and place all occurrences of it as close as possible. After the most frequent character is placed, repeat the same process for remaining characters.

Use HashMap for storing appearance, then priority queue of map.entry, comparator looks like this (max heap, descending order):

private class CompareByValue implements Comparator<Map.Entry<Cell, Integer>> {    @Override    public int compare(Entry<Cell, Integer> lhs,            Entry<Cell, Integer> rhs) {        return rhs.getValue().compareTo(lhs.getValue());    }}

http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

max heap is implemented with priority queue

priority Q example:

// Test.javaimport java.util.Comparator;import java.util.PriorityQueue;public class Test{    public static void main(String[] args)    {        Comparator<String> comparator = new StringLengthComparator();        PriorityQueue<String> queue =             new PriorityQueue<String>(10, comparator);        queue.add("short");        queue.add("very long indeed");        queue.add("medium");        while (queue.size() != 0)        {            System.out.println(queue.remove());        }    }}// StringLengthComparator.javaimport java.util.Comparator;public class StringLengthComparator implements Comparator<String>{    @Override    public int compare(String x, String y)    {        // Assume neither string is null. Real code should        // probably be more robust        // You could also just return x.length() - y.length(),        // which would be more efficient.        if (x.length() < y.length())        {            return -1;        }        if (x.length() > y.length())        {            return 1;        }        return 0;    }}
0 0