Skip to content

Latest commit

 

History

History

0451.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'appearstwicewhile'r'and't'bothappearonce. So'e'mustappearbeforeboth'r'and't'. Therefore"eetr"isalsoavalidanswer.

Example 2:

Input: "cccaaa"Output: "cccaaa"Explanation: Both'c'and'a'appearthreetimes, so"aaaccc"isalsoavalidanswer. Notethat"cacaca"isincorrect, asthesamecharactersmustbetogether.

Example 3:

Input: "Aabb"Output: "bbAa"Explanation: "bbaA"isalsoavalidanswer, but"Aabb"isincorrect. Notethat'A'and'a'aretreatedastwodifferentcharacters.

题目大意

这道题是 Google 的面试题。

给定一个字符串,要求根据字符出现的频次从高到低重新排列这个字符串。

解题思路

思路比较简单,首先统计每个字符的频次,然后排序,最后按照频次从高到低进行输出即可。

close