public class ZConvert {
public String convert(String s, int numRows) { int n = s.length(), r = numRows; if (r == 1 || r >= n) { return s; } StringBuffer[] mat = new StringBuffer[r]; for (int i = 0; i < r; ++i) { mat[i] = new StringBuffer(); } //一个周期元素个数 = numRows + (numRows - 2); int t = 2 * (numRows - 1); //指标字符串共须要 (n/t) + 1 个周期 int tCount = (n/t) + 1; //以后遍历的下标 int index = 0; for (int i = 0; i < tCount; i++) { //以后周期下标 <= 字符串长度 if (index+t <= n) { //截取以后周期的字符 processT(s.substring(index, index+t), numRows, t, mat); } else { processT(s.substring(index, n), numRows, t, mat); } index += t; } StringBuffer ans = new StringBuffer(); for (StringBuffer row : mat) { ans.append(row); } return ans.toString();}public void processT(String sSub, int numRows, int t, StringBuffer[] mat) { int count = t; //子串的长度 小于 周期 if (sSub.length() < t) { //从新赋值子串遍历个数 count = sSub.length(); } for(int i = 0; i < count; i++){ char ele = sSub.charAt(i); //遍历次数 小于 t-(numRows-2) if (i < t-(numRows-2)) { //间接追加以后字符 mat[i].append(ele); } if (i >= t-(numRows-2)) { //遍历次数 大于等于 t-(numRows-2) int matIndex = numRows-(i+1)%numRows-1; // mat的下标 = numRows-(i+1)%numRows-1 mat[matIndex].append(ele); } }}public static void main(String[] args) { String s = "PAYPALISHIRING"; String target = "PAHNAPLSIIGYIR"; String result = new ZConvert().convert(s, 3); Assert.check(target.equals(result), "失败"); System.out.println("胜利!");}
}