7ms easy java solution. kind of bucket sort


  • 0
    S
    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        
        char[] result = new char[s.length()]; 
        int[] probes = new int[numRows + 1];   // Stores the start position of each row
        int[] p = new int[s.length()];         // Stores the corresponding row number 
                                               // of each char in s
        
        for(int i = 0, row = 1, incre = 1; i < s.length(); i++){
            p[i] = row;                        // saving row number
            probes[row]++;                     // counting how many characters in this row
            
            if (row == 1) incre = 1;
            else if(row == numRows) incre = -1;
            
            row += incre;
        }
        
        for (int i = 2; i < probes.length; i++){
            probes[i] += probes[i - 1];         // computing the start position of each row
        }
        
        for(int i = 0; i < p.length; i++){
            result[probes[p[i] - 1]++] = s.charAt(i); // Sorting string. 
        }                                             // putting char to desired position
        
        return String.valueOf(result);
    }

Log in to reply
 

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