zoukankan      html  css  js  c++  java
  • Rearrange a string so that all same characters become d distance away

    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
    摘自:http://www.geeksforgeeks.org/rearrange-a-string-so-that-all-same-characters-become-at-least-d-distance-away/

    这题就是贪心算法。对于字符串处理来讲,如果不care最终的符号序,就要以考虑用统计重排的方法。

    1. 统计所有字符的出现频率;

    2. 按出现频率从高到低优先填好所有字符;

    如果全部都是ASCII码,共出现m个不同字符,第2步,可以:

    1. 用最大堆来做,也可以直接排序,时间复杂度都是O(n+mlgm),空间复杂度就是O(m)。因为m<256<<n,所以最终复杂度也可以说是O(n)。

    2. 也可以直接用一个vector<list<char> >记录每个频率下的字符来做。用vector<list<char> >就是O(2n)的时间复杂度了。空间复杂度高点,O(n)。

  • 相关阅读:
    团队展示
    原型设计(结对第一次)
    第二次作业——个人项目实战
    第一次作业--准备篇
    课程作业四
    课程作业三
    课程作业二
    课程作业一
    图像处理------ 一阶微分应用 (转载)
    dennis gabor 从傅里叶(Fourier)变换到伽柏(Gabor)变换再到小波(Wavelet)变换(转载)
  • 原文地址:https://www.cnblogs.com/linyx/p/4083424.html
Copyright © 2011-2022 走看看