Naive O(n^2) java solution


  • 0
    M
    public class Solution {
        public String frequencySort(String s) {
            if(s.length()<1){
                return s;
            }
            Map<Character, Integer> myMap = new HashMap<Character, Integer>();
            
            for(int i=0;i<s.length();i++){
                if(!myMap.containsKey(s.charAt(i))){
                    myMap.put(s.charAt(i), 1);
                }
                else{
                    int val = myMap.get(s.charAt(i));
                    myMap.put(s.charAt(i), ++val);
                }
            }
            StringBuffer sb = new StringBuffer();
            while(!myMap.isEmpty()){
                Iterator it = myMap.entrySet().iterator();
                Character ch = null;
                Integer max = 0;
                if(!it.hasNext()){
                    myMap.clear();
                }
                if(myMap.entrySet().size()<1){
                    myMap.clear();
                }
                for (Map.Entry<Character, Integer> entry : myMap.entrySet()) {
                    Character key = entry.getKey();
                    Integer value = entry.getValue();
                    if(value>max){
                        max = value;
                        ch = key;
                    }
                }
                for(int i=0;i<max;i++){
                    sb.append(ch);
                }
                myMap.remove(ch);
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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