A mathematic solution


  • 0

    This is a mathematic solution of the problem. Beating 47% is not very bad. Hope it can be intuitive and helpful. Any comments are welcome.

    public String convert(String s, int numRows) {
            StringBuilder ret = new StringBuilder();
            if(numRows <= 0) return ret.toString();
            if(numRows == 1) return s;
            
            // create a string for each level
            StringBuilder[] strs = new StringBuilder[numRows];
            for(int i = 0; i < numRows; i ++){
                strs[i] = new StringBuilder();
            }
            
            for(int i = 0; i < s.length(); i ++){
                // get the current char
                char temp = s.charAt(i);
                // calculate the number of each loop; for example "PAYP" can be a loop while "ALIS" is the next one
                int loop = 2 * numRows - 2;
                // calculate the index of string which the char can be put
                int j = (i % loop) < numRows ? (i % loop) : (loop - i % loop);
                strs[j].append(temp);
            }
            
            for(int i = 0; i < strs.length; i ++){
                ret.append(strs[i].toString());
            }
            return ret.toString();
        }
    

Log in to reply
 

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