public class Solution {
    public string FrequencySort(string s) {
        var dic = new Dictionary<char, int>();
            foreach (var c in s)
            {
                if (!dic.ContainsKey(c))
                {
                    dic.Add(c, 1);
                }
                else
                {
                    dic[c]++;
                }
            }

            var list = dic.OrderByDescending(x => x.Value).ToList();
            StringBuilder sb = new StringBuilder();
            foreach (var l in list)
            {
                var cha = l.Key;
                var times = l.Value;
                while (times > 0)
                {
                    sb.Append(cha);
                    times--;
                }
            }
            return sb.ToString();
    }
}

https://leetcode.com/problems/sort-characters-by-frequency/#/description

 

补充一个python的实现:

 1 import collections
 2 
 3 class Solution:
 4     def frequencySort(self, s: str) -> str:
 5         count = collections.Counter(s)
 6         li = sorted(count.items(), key=lambda d:d[1], reverse = True)
 7         result = ''
 8         for i in range(len(li)):
 9             result += li[i][0] * li[i][1]
10         return result

 

posted on 2017-05-09 16:12  Sempron2800+  阅读(152)  评论(0编辑  收藏  举报