Simple accepted Java code with Arrays.sort


  • 0
    U
    public String frequencySort(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        
        char[] bb = s.toCharArray();
        Arrays.sort(bb);
        
        StringBuilder sb = new StringBuilder();
        sb.append(bb[0]);
        for (int i = 1; i < bb.length; i++) {
            if (bb[i] != bb[i-1]) {
                sb.append("`");
            }
            sb.append(bb[i]);
        }
        
        String[] str = sb.toString().split("`");
        
        Arrays.sort(str, new Comparator<String>() {
            
                public int compare(String s1, String s2) {
                    if(s1.length() > s2.length()) {
                        return -1;
                    } else if (s1.length() < s2.length()) {
                        return 1;
                    }
                    if (s1.charAt(0) > s2.charAt(0)) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
        });
        
        StringBuilder res = new StringBuilder();
        for (String ss : str) {
            res.append(ss);
        }
        return res.toString();
    }

Log in to reply
 

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