题目:
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"
.
解决:
1. 要知道zigzag形状。
2. 周期计算位置,注意特殊位置。
/** * 把一字符串排成Zigzag形状,然后按行重新组起来。通过计算周期性位置。 * Zigzag形状: * # # * # # # # * # # # # * # # * @author Administrator * */ public class ZigzagConvert { public String convert(String s, int nRows) { int len = s.length(); if (len <= 1 || nRows == 1) return s; int zouqi = nRows > 2 ? (nRows + nRows - 2) : nRows;//计算周期,一竖一上折 StringBuffer sb = new StringBuffer(); for (int i = 0; i < nRows; i++) {//遍历行 int idx = i; int idxy = nRows + nRows - 2 - i; while (true) { if (idx >= len) break; sb.append(s.charAt(idx));//一竖 idx += zouqi; if (i > 0 && idxy > nRows - 1) {//一上折,可能不存在 if (idxy >= len) break; sb.append(s.charAt(idxy)); idxy += zouqi; } } } return sb.toString(); } public static void main(String[] args) { ZigzagConvert zz = new ZigzagConvert(); int nRows = 2; String s = zz.convert("ABCDE", nRows); System.out.println(s); } }
参考: