zoukankan      html  css  js  c++  java
  • 451. 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' 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.
    给定一个字符串,根据字符的频率按顺序排序。
    1. /**
    2. * @param {string} s
    3. * @return {string}
    4. */
    5. var frequencySort = function (s) {
    6. let m = {};
    7. for (let i in s) {
    8. let c = s[i];
    9. if (m[c]) {
    10. m[c]++;
    11. } else {
    12. m[c] = 1;
    13. }
    14. }
    15. let arr = [];
    16. for (let i in m) {
    17. let d = {};
    18. d.str = i;
    19. d.time = m[i];
    20. arr.push(d);
    21. }
    22. arr.sort((a, b) => {
    23. return b.time - a.time;
    24. });
    25. let res = "";
    26. for (let i in arr) {
    27. let item = arr[i];
    28. res += item.str.repeat(item.time);
    29. }
    30. return res;
    31. };
    32. // let s = "Aabb";
    33. // console.log(frequencySort(s));






  • 相关阅读:
    虚拟机中按键切回windows系统界面快捷键
    余数
    质数(素数)判断代码实现
    =excel========》函数使用
    python 正则表达式规则
    linux常用命令详解
    c指针
    visual studio 2015 开发时常见问题的解决方案
    python装饰器
    构造方法
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/7679664.html
Copyright © 2011-2022 走看看