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)
1 public class Solution { 2 public String convert(String s, int numRows) { 3 if (s == null || numRows < 2 || s.length() <= numRows) { 4 return s; 5 } 6 StringBuilder sb = new StringBuilder(s.length()); 7 int gap = 2 * numRows - 2; 8 for (int i = 0; i < numRows; i++) { 9 for (int j = i; j < s.length(); j += gap) { 10 sb.append(s.charAt(j)); 11 if (i > 0 && i < numRows - 1) { 12 int t = j + gap - 2 * i; 13 if (t < s.length()) { 14 sb.append(s.charAt(t)); 15 } 16 } 17 } 18 } 19 return sb.toString(); 20 } 21 }

浙公网安备 33010602011771号