Java use Collections.sort()


  • 0
    F

    I knew this is not best solution, but this is what I can fast to got idea~

    public class Solution {
    public String frequencySort(String s) {
        StringBuilder result = new StringBuilder();
        if(s == "" || s.length() == 0) return "";
        // scan s count char appear time make hash map
        char[] sArr = s.toCharArray();
        Map<Character, Integer> hash = new HashMap<Character, Integer>();
        for (Character c : sArr) {
            if (hash.containsKey(c)) {
                hash.put(c, hash.get(c) + 1);
            } else {
                hash.put(c, 1);
            }
        }
        // Sort HashMap
        List<Map.Entry<Character,Integer>> list = new ArrayList<Map.Entry<Character,Integer>>(hash.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        //Create String
        for (Map.Entry<Character, Integer> element : list) {
            int appearTime = element.getValue();
            while (appearTime > 0) {
                result.append(element.getKey());
                appearTime--;
            }
        }
        return result.toString();
    }
    

    }


Log in to reply
 

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