java.lang.Object
g0401_0500.s0451_sort_characters_by_frequency.Solution

public class Solution extends Object
451 - Sort Characters By Frequency.<p>Medium</p> <p>Given a string <code>s</code>, sort it in <strong>decreasing order</strong> based on the <strong>frequency</strong> of the characters. The <strong>frequency</strong> of a character is the number of times it appears in the string.</p> <p>Return <em>the sorted string</em>. If there are multiple answers, return <em>any of them</em>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> s = &ldquo;tree&rdquo;</p> <p><strong>Output:</strong> &ldquo;eert&rdquo;</p> <p><strong>Explanation:</strong> &lsquo;e&rsquo; appears twice while &lsquo;r&rsquo; and &lsquo;t&rsquo; both appear once. So &lsquo;e&rsquo; must appear before both &lsquo;r&rsquo; and &lsquo;t&rsquo;. Therefore &ldquo;eetr&rdquo; is also a valid answer.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> s = &ldquo;cccaaa&rdquo;</p> <p><strong>Output:</strong> &ldquo;aaaccc&rdquo;</p> <p><strong>Explanation:</strong> Both &lsquo;c&rsquo; and &lsquo;a&rsquo; appear three times, so both &ldquo;cccaaa&rdquo; and &ldquo;aaaccc&rdquo; are valid answers. Note that &ldquo;cacaca&rdquo; is incorrect, as the same characters must be together.</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> s = &ldquo;Aabb&rdquo;</p> <p><strong>Output:</strong> &ldquo;bbAa&rdquo;</p> <p><strong>Explanation:</strong> &ldquo;bbaA&rdquo; is also a valid answer, but &ldquo;Aabb&rdquo; is incorrect. Note that &lsquo;A&rsquo; and &lsquo;a&rsquo; are treated as two different characters.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= s.length <= 5 * 10<sup>5</sup></code></li> <li><code>s</code> consists of uppercase and lowercase English letters and digits.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details