1. 程式人生 > >451. Sort Characters By Frequency(python+cpp)

451. Sort Characters By Frequency(python+cpp)

題目:

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.

解釋:
先統計,再根據出現的頻率排序。
在python中需要用item()函式把字典鍵值對轉成元組,在c++中需要轉成pair 陣列,而且要自己實現一下排序函式。
python程式碼:

from collections import Counter
class Solution(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        _dict=Counter(s)
        sort_dict=sorted
(_dict.items(),key=lambda item:item[1],reverse=True) result='' for item in sort_dict: result+=item[0]*item[1] return result

c++程式碼:

#include <map>
using namespace std;
class Solution {
public:
    string frequencySort(string s) {
        map<char,int> _map;
        for(auto letter:s)
            _map[letter]+=1;
        //把map轉換成陣列
        vector<pair<char, int>> map_list(_map.begin(),_map.end());
        sort(map_list.begin(),map_list.end(),cmp);
        string result="";
        for (auto item :map_list)
        {
            string tmp(item.second, item.first);
            result+=tmp;
        }
        return result;
    }
    static bool cmp(const pair<char, int>& item1,const pair<char, int>& item2)
    {
        return item1.second>item2.second;
    }
};

總結:
python中,d.items()實際上是將d轉換為可迭代物件,迭代物件的元素為(‘lilee’,25)、(‘wangyan’,21)、(‘liqun’,32)、(‘lidaming’,19),items()方法將字典的元素轉化為了元組,而這裡key引數對應的lambda表示式的意思則是選取元組中的第二個元素作為比較引數(如果寫作key=lambda item:item[0]的話則是選取第一個元素作為比較物件,也就是key值作為比較物件。lambda x:y中x表示輸入引數,y表示lambda函式的返回值),所以採用這種方法可以對字典的value進行排序。注意排序後的返回值是一個list,而原字典中的鍵值對對被轉換為了list中的元組。