首页 > 编程语言 > 详细

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

时间:2017-10-17 00:39:56      阅读:279      评论:0      收藏:0      [点我收藏+]

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 按频率排序字符

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!