ZigZagConversion.java /** * 6. ZigZag Conversion * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: * (you may want to display this pattern in a fixed font for better legibility) * P A H N * A
/** * 6. ZigZag Conversion * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: * (you may want to display this pattern in a fixed font for better legibility) * P A H N * A P L S I I G * Y I R * And then read line by line: "PAHNAPLSIIGYIR" * Write the code that will take a string and make this conversion given a number of rows: * string convert(string text, int nRows); * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". * How to fix it? My Solution is: * There is a pointer which scan each row, * if is first row or last row, then you can find split: = (2*rowNum - 2) * else you can find: splitUp = (2*(rowNum-i)-2) and splitDown=i*2 * so it's easy enough to convert it * @param s * @param numRows * @return */ public static String convertZigzag(String s, int numRows) { int length = s.length(); if (length <= 1 && numRows <= 1) { return s; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < numRows; i++) { // 处理第一行和最后一行 if (i == 0 || i == numRows - 1) { for (int j = i; j < s.length(); j += (2 * numRows) - 2) { sb.append(s.charAt(j)); } continue; } // 处理中间行 int tmp = i; int tmpCount = 0; boolean isUp = true; boolean isFirst = true; while (tmp < s.length()) { if (isFirst) { if (tmp < numRows) { sb.append(s.charAt(tmp)); tmpCount++; isFirst = false; } } if (isUp) { tmp += 2 * (numRows - i) - 2; } else { tmp += i * 2; } if (tmp < s.length()) { sb.append(s.charAt(tmp)); tmpCount++; } if (tmpCount % 2 == 0) { isUp = false; } } } return sb.toString(); }