leetcode 6. Z 字形变换
public class Solution { public String convert(String s, int numRows) { if(numRows == 1){ return s; } StringBuilder stringBuilder = new StringBuilder(); int len = s.length(); int t = 2 * numRows - 2; int l1 = numRows / t + 1; //第一行 int i = 0; while(true){ int i1 = t * i; if(i1 >= len){ break; } stringBuilder.append(s.charAt(i1)); i++; } //中间行 for(int j = 2;j < numRows;j++){ i = 0; while(true){ int i2 = j - 1 + t * i; if(i2 >= len){ break; } stringBuilder.append(s.charAt(i2)); int i1 = t - j + 1 + t * i; if(i1 >= len){ break; } stringBuilder.append(s.charAt(i1)); i++; } } //最后一行 i = 0; while(true){ int i3 = numRows - 1 + t * i; if(i3 >= len){ break; } stringBuilder.append(s.charAt(i3)); i++; } return stringBuilder.toString(); } public static void main(String[] args) { Solution solution = new Solution(); String s = "PAYPALISHIRING"; String ans = solution.convert(s,3); System.out.println(ans); } }