Javascript solution


  • 0
    N

    Basically, what I did was:

    1. record the frequency of each character. Place them in a map
    2. have an array (cacheFreq). Let's say if 'i' and 'a' both appear once,
      cacheFreq[1] will equal to 'ia'. If 'k' and 'h' both appear three times, cacheFreq[3] will be 'hhhkkk' or 'kkkhhh'
    3. Output what you have in cacheFreq, counting from the highest index. Skip the undefined elements, and remember to sort!

    var frequencySort = function(s) {
    s = s.split('');
    var map = new Map();
    s.forEach(function(ch){
    if (map.has(ch))
    map.set(ch, map.get(ch) + 1)
    else
    map.set(ch, 1)
    })

    var cacheFreq = [];
    var currentStr = ''
    map.forEach(function(freq, ch){
        var count = freq;
        while (count){
             currentStr += ch;
             count--;
        }
        if (cacheFreq[freq]){
            cacheFreq[freq] += currentStr
        }
        else {
            cacheFreq[freq] = currentStr;
        }
        currentStr = ''
        
    })
    var index = cacheFreq.length - 1;
    var answer = '';
    while (index > 0){
        if (cacheFreq[index])
            answer += cacheFreq[index].split('').sort().join('');
        index--;
    }
    return answer;
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.