451. Sort characters by Frequency sorting characters by frequency

Source: Internet
Author: User

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" was incorrect, as the same characters must be together.

Example 3:

Input:"Aabb"Output:"Bbaa"Explanation:"Bbaa" is also a valid answer and "Aabb" is incorrect. Note that ' a ' and ' a ' is treated as the different characters.
given a string, sort by the frequency of the 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));




From for notes (Wiz)

451. Sort characters by Frequency sorting characters by frequency

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.