451. Sort Characters By Frequency【力扣】

题意理解

将字符串按频率从大到小输出

问题分析

用hash表,然后选择排序

用一个数组存放字符串中的字符和出现的频率。然后从这个数组中每次选择一个最大的数出来,按频率输出,然后将其频率置为0,直到数组没有字符串字母。

其他

看到另一个高分解法,用map+vector来做,思路是map保存字符串字符和频率对信息。vector的元素是字符串(每种字符重复出现的字符串),元素的下标以字符出现的数量为准。然后倒着输出就可以。

链接

https://leetcode-cn.com/submissions/detail/14719631/

    string frequencySort(string s) {
        string result;
        int dict[128] = {0};
        for(int i = 0; i < s.size(); i ++)
        {  
            dict[s[i]]++; 
        }
        for(int i = 0; i < 128; i ++)   //每次找一个最大值
        {
            int maxIndex = 0;   //记录最大的索引
            for(int j = 0; j < 128; j ++)   //每次在字典里遍历一遍
            {    
                if (dict[j] > dict[maxIndex])
                {   
                    maxIndex = j;
                }
            }  
            if (maxIndex != 0)
            {
                while(dict[maxIndex]--)
                {
                    result.push_back(maxIndex);
                }
            }
        }

        
        cout << result << endl;            
        
        return result;
    }

猜你喜欢

转载自blog.csdn.net/xiexie1357/article/details/88565609