Rearrange a string so, all same characters become D distance away

Source: Internet
Author: User

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

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

Examples:input:  "ABB", D = 2Output: "Bab" input:  "AACBBC", d = 3Output: "ABCABC" Input: "Geeksforgeeks", d = 3Output : egkegkesfesorinput:  "AAA",  d = 2output:cannot be rearranged

1  Public classsolution{2     3      Public Static intMAX = 26;4     Static classCharfreq {5         CharC;6         intF;7          PublicCharfreq (CharCintf) {8              This. C =C;9              This. F =F;Ten         } One     } A      -      Public Static voidMain (String []args) { -String str = rearrange ("Geeksforgeeks", 3); the         if(str! =NULL) - System.out.println (str); -     } -       +      Public StaticString rearrange (String str,intk) { -         if(Str.length () <= 1)returnstr; +           Acharfreq[] CF =NewCharfreq[max]; at         intCount = 0;//Number of different characters -          -          for(inti=0; i<max; i++) { -Cf[i] =NewCharfreq ((Char) (' A ' +i), 0);  -         } -          in          for(inti=0; I<str.length (); i++) { -             CharCH =Str.charat (i); tocf[ch-' A '].f++; +             if(cf[ch-' a '].f = = 1) count++; -         } the          * buildheap (cf, MAX); $         Panax Notoginseng         Char[] str1 =New Char[Str.length ()]; -         Boolean[] Occu =New Boolean[Str.length ()];//judge if the seat is occupied the          for(inti = 0; i<count; i++) { +Charfreq chfreq = Extractmax (cf, max-i); A             intPT =i; the              while(occu[pt]) pt++;//find The first place and that's not occupied +              -              for(intj=0; j<chfreq.f; J + +) { $                 if(PT >=str1.length) $                     return NULL; -STR1[PT] =chfreq.c; -OCCU[PT] =true; thePT + =K; -             }Wuyi         } the         return NewString (str1); -     } Wu      -     Private Static voidBuildheap (charfreq[] CF,intsize) { About         inti = (size-1)/2; $          while(i>=0) { - maxheapify (cf, I, size); -i--; -         } A     } +      the     Private Static voidSwap (Charfreq cf1, Charfreq cf2) { -         Charc =cf1.c; $         intf =cf1.f; thecf1.c =cf2.c; theCF1.F =cf2.f; theCF2.C =C; theCF2.F =F; -     } in      the     Private Static voidMaxheapify (charfreq[] CF,intNodeintsize) { the         intL = node * 2 + 1; About         intr = Node * 2 + 2; the         intlargest =node; the         if(L < size && CF[L].F >cf[node].f) { thelargest =l; +         } -         if(R < size && CF[R].F >cf[largest].f) { thelargest =R;Bayi         } the         if(Largest! =node) { the swap (Cf[node], cf[largest]); - maxheapify (cf, largest, size); -         } the     } the      the     Private StaticCharfreq Extractmax (charfreq[] CF,intsize) { theCharfreq max = cf[0]; -Cf[0] = cf[size-1]; theCF[SIZE-1] =NULL; theMaxheapify (cf, 0, size-1); the         returnMax;94     }  the}

Analysis:

Time Complexity: Time complexity of above implementation is O (n + mlog (MAX)). Here n was the length of STR, M is count of distinct characters in str[] and MAX are maximum possible different characters. Max is typically (a constant) and M is smaller than MAX. So the time complexity can considered as O (n).

More analysis:
The above code can optimized to store is only m characters in heap and we have kept it this-to-keep the code simple. So the time complexity can is improved to O (n + mlogm). It doesn ' t much matter through as MAX is a constant.

Also, the above algorithm can be implemented using a O (MLOGM) sorting algorithm. The first steps of above algorithm remain same. Instead of building a heap, we can sort the freq[] array in non-increasing order of frequencies and then consider all Char Acters one by one from sorted array.

Rearrange a string so, all same characters become D distance away

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.