C#版:
public class Solution { public string Convert(string s, int numRows) { char[] c = s.ToArray(); int len = c.Length; StringBuilder[] sb = new StringBuilder[numRows]; for (int i = 0; i < sb.Length; i++) { sb[i] = new StringBuilder(); } int j = 0; while (j < len) { for (int idx = 0; idx < numRows && j < len; idx++) // vertically down sb[idx].Append(c[j++]); for (int idx = numRows - 2; idx >= 1 && j < len; idx--) // obliquely up sb[idx].Append(c[j++]); } for (int idx = 1; idx < sb.Length; idx++) sb[0].Append(sb[idx]); return sb[0].ToString(); } }
https://leetcode.com/problems/zigzag-conversion/#/description
Java版:
1 class Solution { 2 public String convert(String s, int numRows) { 3 char[] c = s.toCharArray(); 4 int len = c.length; 5 StringBuilder[] sBuilder = new StringBuilder[numRows]; 6 for (int i = 0; i < sBuilder.length; i++) { 7 sBuilder[i] = new StringBuilder(); 8 } 9 int j = 0; 10 while (j < len) { 11 for (int idx = 0; idx < numRows && j < len; idx++) { 12 sBuilder[idx].append(c[j++]); 13 } 14 for (int idx = numRows - 2; idx >= 1 && j < len; idx--) { 15 sBuilder[idx].append(c[j++]); 16 } 17 } 18 for (int idx = 1; idx < sBuilder.length; idx++) { 19 sBuilder[0].append(sBuilder[idx]); 20 } 21 return sBuilder[0].toString(); 22 } 23 }