java ,beat 98.99%, how to beat 100%?


  • 0
    L

    using array is faster than HashMap

    public class Solution {
        public String frequencySort(String s) {
            int[] d = new int[91];
            int f = s.length();
            char[] ss = s.toCharArray();
            for(int m=0;m<f;m++){
                int t = ss[m]-' ';
                d[t]++;
            }
            StringBuilder[] m1 = new StringBuilder[f+1];
            for(int i = 0 ; i < 91;){
                int num = d[i];
                if(m1[num]==null){
                    StringBuilder sb = new StringBuilder();
                    sb.append((char)(i+' '));
                    m1[num] = sb;
                }else{
                    m1[num].append((char)(i+' '));
                }
                if((i>=0 && i<25)||(i>=33 &&i<60)||(i>=65 &&i<=90)){
                    i++;
                }else if(i==25){
                    i = 33;
                }else if(i==60){
                    i = 65;
                }
            }
            StringBuilder all = new StringBuilder();
            for(int i = f ; i>=0 ; i--){
                if(m1[i]==null)continue;
                StringBuilder t = m1[i];
                int len = t.length();
                for(int j =0 ;j<len ;j++){
                    char n = t.charAt(j);
                    int v = i;
                    while(v-->0){
                        all.append(n);
                    }
                }
            }
            return all.toString();        
        }
    } 
    

Log in to reply
 

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