Java solution by calculating index directly


  • 0
    C

    By writing down some examples, we can see that the difference of index for the first line and last line are 2 * (numRows - 1), and for other lines that has varying difference for the index, it is the sum of the two varying distance. So we have this solution.

    public String convert(String ss, int numRows) {
        if (numRows == 1 || ss.length() <= numRows) return ss;
        int diff = 2 * (numRows - 1); 
        char[] s = ss.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            int ind = i, dis = i * 2;
            while (ind < s.length) {
                sb.append(s[ind]);
                if (dis != diff) dis = diff - dis;        
                ind += dis;
            }
        }
        return sb.toString();
    }

Log in to reply
 

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