static string RearrangeStringKApart(string str, int k) { // populate dictionary // populate max heap // get the top element // add to the result , decrement the counter // add the element to Queue <Element> queue = new Queue <Element>(); Dictionary <char, int> dict = new Dictionary <char, int>(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { if (!dict.ContainsKey(str[i])) { dict.Add(str[i], 0); } dict[str[i]]++; } MaxHeap maxHeap = new MaxHeap(dict.Count); foreach (var entry in dict) { maxHeap.Insert(new Element(entry.Key, entry.Value)); } while (maxHeap.Count > 0) { Element current = maxHeap.Delete(); sb.Append(current.Character); current.Frequency--; if (current.Frequency > 0) { queue.Enqueue(current); } if (queue.Count == k) { maxHeap.Insert(queue.Dequeue()); } } return(sb.Length == str.Length ? sb.ToString() : ""); }
// create a dictionary with character and frequency // Create a MaxHeap // get the top element add to the string and decrement the count // do not push it back get the next element , // push the previous string back to heap if count >0 and heap is not empty static string RearrangeString(string str) { Dictionary <char, int> dict = new Dictionary <char, int>(); foreach (char c in str) { if (!dict.ContainsKey(c)) { dict.Add(c, 0); } dict[c]++; } MaxHeap maxHeap = new MaxHeap(dict.Count); foreach (var entry in dict) { maxHeap.Insert(new Element(entry.Key, entry.Value)); } Element previous = null; Element current = null; StringBuilder sb = new StringBuilder(); while (maxHeap.Count > 0) { current = maxHeap.Delete(); if (previous != null && previous.Frequency > 0) { maxHeap.Insert(previous); } sb.Append(current.Character); current.Frequency--; previous = current; } return(sb.Length == str.Length ? sb.ToString() : ""); }