2020年5月22日 星期五

Leetcode題解 Python & C#:五月挑戰DAY22 Sort Characters By Frequency

給一個字串,要以字母的出現次數重新排列。

首先要有可以統計字母的方式,用 hash table 可以很容易記錄哪些字的有出現與其次數。

python 有 collections.Counter 可以快速轉換。

Python
class Solution:
    def frequencySort(self, s: str) -> str:
        counter = Counter(s)
        result = ""
        for each in sorted(counter.items(), key = lambda x: x[1], reverse = True):
            result += each[0] * each[1]
        return result 
C#
public class Solution {
    public string FrequencySort(string s) {
        var counter = new Dictionary();
        foreach(char c in s)
        {
            if(counter.ContainsKey(c))
            {
                counter[c] += 1;
            }
            else
            {
                counter[c] = 1;
            }
        }
        var result = new StringBuilder();
        foreach(var item in counter.OrderByDescending(x=>x.Value))
        {
            result.Append(item.Key, item.Value);
        }
        return result.ToString();
    }
}