微信小程序开发之小程序架构篇的图解与分析
740
2022-09-04
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.
思路: hashmap求frequency加排序,排序可以用bucket sort or heap sort。
class Solution { public String frequencySort(String s) { Map
/** * @param {string} s * @return {string} */var frequencySort = function(s) { const len = s.length if (!len) { return s } const map = new Map() const temp = [] let str = '' for (let i = 0; i < len; i++) { const char = s[i] if (!map.has(char)) { map.set(char, 1) } else { map.set(char, map.get(char) + 1) } } map.forEach((val, key) => { temp.push({ val, key }) }) temp.sort((a, b) => b.val - a.val) temp.forEach(item => { str += item.key.repeat(item.val) }) return str};
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~