堆排序——LeetCode451. Sort Characters By Frequency

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/82888790

堆排序——LeetCode451. Sort Characters By Frequency

题目

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters

思路

这道题的意思是给一个字符串,要求对字符串里的字符顺序进行调整,使得调整后字符串里的字符是根据其出现频率从高到低排列。因此首先遍历这个字符串,利用map获得每个字符出现的频率,然后再使用堆排序,最后根据堆排序的结果重新构建新的字符串。

代码


typedef struct node{
    char ch;
    int fre;
};

class Solution {
public:
    vector<node>number;

    void maximun(int i, int heap_size) {
        int l, r, m;
        node temp;
        l = 2*i; r = 2*i+1; m = i;
        temp = number[i];
        if(l<=heap_size && number[l-1].fre>number[i-1].fre) {
            m = l;
            temp = number[l-1];
        }
        if(r<=heap_size && number[r-1].fre>number[m-1].fre) {
            m = r;
            temp = number[r-1];
        }
        if(m!=i) {
            number[m-1] = number[i-1];
            number[i-1] = temp;
            maximun(m, heap_size);
        }
    }

    void heap_build() {
        int i, j;
        for(i = number.size()/2; i>0; i--) {
            maximun(i, number.size());
        }
    }

    void heap_sort() {
        heap_build();
        int len, i, j;
        node temp;
        len = number.size();
        while(len>1) {
            temp = number[0];
            number[0] = number[len-1];
            number[len-1] = temp;
            maximun(1, len-1);
            len--;
        }
    }

    string frequencySort(string s) {
        int i, j;
        string res = "";
        map<char, int> m;
        map<char, int>::iterator iter;
        m.clear();
        for(i=0; i<s.length(); i++) {
            if(m.count(s[i])==0) {
                m[s[i]] = 1;
            }
            else {
                m[s[i]]++;
            }
        }
        number.clear();
        iter = m.begin();
        while(iter!=m.end()) {
            node t;
            t.ch = iter->first;
            t.fre = iter->second;
            number.push_back(t);
            iter++;
        }
        heap_sort();

        stringstream str;
        for(i=number.size()-1; i>=0; i--) {
            j = number[i].fre;
            while(j--) {
                res += number[i].ch;
               // res.append(number[i].ch.tostring());
            }
        }

        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/hh66__66hh/article/details/82888790