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

Source: Internet
Author: User

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 either possible rearrangements, the output shocould be one of the possible rearrangements. if no such arrangement is possible, that shoshould 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
From: http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

This is the greedy algorithm. For string processing, if you do not care about the final signed order, you need to consider the method of statistical shuffling.

1. Count the occurrence frequency of all characters;

2. Fill in all characters first from high to low according to the frequency of occurrence;

If all the characters are ASCII codes, a total of m different characters are displayed. In step 1, you can:

1. The largest heap can be used for direct sorting. The time complexity is O (n + mlgm), and the space complexity is O (m ). Because m <256 <n, the final complexity is O (n ).

2. You can also use a vector <list <char> to record the characters at each frequency. Using vector <list <char> is the time complexity of O (2n. High space complexity, O (n ).

 

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

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.