JAVA solution - maybe easy and clear


  • 0
    S

    Draw the result draft (such as "123456789", 3), and calculate the distance between adjacent elements in each line.Then you will know why I wrote this ;)

    public class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 1 || numRows >= s.length()) {
                return s;
            }
    
            char[] c = s.toCharArray();
            StringBuffer sb = new StringBuffer();
    
            int first = 2 * numRows - 2;
            int second = 0;
            for (int j = 0; j < numRows; j++) {
                for (int i = j; i < s.length();) {
                	sb.append(c[i]);
                    if (j == 0 || j == numRows - 1) {
                        i += 2 * numRows - 2;
                    } else {
                        i += first;
                        if(i < s.length()){
                        	sb.append(c[i]);
                        }
                        i += second;
                    }
                }
                first -= 2;
                second += 2;
            }
    
            return sb.toString();
        }
    }
    

Log in to reply
 

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