码迷,mamicode.com
首页 > 编程语言 > 详细

451. Sort Characters By Frequency 按频率排序字符

时间:2017-10-17 01:09:25      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:title   mil   different   round   put   var   val   color   print   

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));






451. Sort Characters By Frequency 按频率排序字符

标签:title   mil   different   round   put   var   val   color   print   

原文地址:http://www.cnblogs.com/xiejunzhao/p/7679664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!