Given a non-empty string str and an integer K, rearrange the string such, the same characters is at least distance K from each of the other.
All input strings is given in lowercase letters. If It is not a possible to rearrange the string, return an empty string ""
.
Example 1:
str = "AABBCC", K = 3Result: "ABCABC" the same letters is at least distance 3 from all other.
Example 2:
str = "Aaabc", K = 3 Answer: "It is not possible to rearrange the string.
Example 3:
str = "AAADBBCC", K = 2Answer: "ABACABCD" Another possible answer is: "ABCABCDA" the same letters was at least distance 2 fr Om each of the other.
Credits:
Special thanks to @elmirap for adding this problem and creating all test cases.
This problem gives us a string str, and an integer k, let us re-order the string str, so that the same characters between the distance is not less than K, the difficulty of the problem is marked hard, it appears that the fuel-saving lamp. Indeed, the solution to this problem is used in hash tables, heaps, and greedy algorithms. This problem I first think of the algorithm did not pass the large set of OJ time-out, the following method is to refer to the online solution of the great God, found very ingenious. We need a hash table to build the mappings between the characters and their occurrences, and then we need a heap to hold each of these heap mappings, sorted by the number of occurrences. Then if the heap is not empty we start the loop, we find a smaller value between the length of K and STR, and then walk from 0 to this smaller value, and for each value traversed, if the heap is empty at this point, the position cannot be filled with characters, returns an empty string, or we take a pair of mappings from the top of the heap, Then add the letter to the result res, at this time the number of mappings minus 1, if the number after 1 is still greater than 0, then we will add this map to the temporary set V, and the number of Str Len minus 1, after traversing once, we put the temporary collection of mappings in the heap, see the code as follows:
classSolution { Public: stringRearrangestring (stringStrintk) {if(k = =0)returnstr; stringRes; intLen = (int) str.size (); Unordered_map<Char,int>m; Priority_queue<pair<int,Char>>Q; for(auto A:str) + +M[a]; for(Auto it = M.begin (); It! = M.end (); + +it) {Q.push ({it->second, it->First }); } while(!Q.empty ()) {Vector<pair<int,int>>v; intCNT =min (k, Len); for(inti =0; I < CNT; ++i) {if(Q.empty ())return ""; Auto T=q.top (); Q.pop (); Res.push_back (T.second); if(--t.first >0) V.push_back (t); --Len; } for(Auto A:v) Q.push (a); } returnRes; }};
Resources:
Https://leetcode.com/discuss/108174/c-unordered_map-priority_queue-solution-using-cache
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Rearrange string K Distance Apart separated by distance for the rearrangement of strings