1. 程式人生 > >451. Sort Characters By Frequency 按頻率排序字符

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

給定 plan string eight rac 筆記 bottom let hat

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




來自為知筆記(Wiz)

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