unable to pass last test case. Unable to figure out why for Sort Charcter by Frequency?


  • 0
    S

    Uses a array and a comparator which sorts using count of character. TimeComplexity - nlogn and Space - O(2n)

    public class Solution {
        
            public String frequencySort(String s) {
           if(s==null || s.length() < 3) return s;
            //char[] charArray = s.toCharArray();
            Map<Character,Integer> map = new HashMap<Character, Integer>(); 
            
            int count=0;
            Character[] charArray = new Character[s.length()];
            
            for(int i=0;i < s.length(); i++)
            {
            	charArray[i]=s.charAt(i);
            	
                Integer nu = !map.containsKey(charArray[i]) ? 1 : map.get(charArray[i])+1;
                map.put(charArray[i],nu);
            }
            
            Arrays.sort(charArray, new Comparator<Character>(){
                public int compare(Character a, Character b)
                {
                    if(map.get(a) > map.get(b)){
                        return -1;
                    }
                    else if(map.get(a) ==map.get(b)){
                        return a.compareTo(b);
                        //return 0;
                    }
                    else return 1;
                }
                
            });
            
            StringBuilder sb = new StringBuilder();
            
            for(Character c : charArray)
             sb.append(c);
             
            return sb.toString();   
            
        }
        
    }
    
    

Log in to reply
 

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