# #6 Z字形变换

``````L   C   I   R
E T O E S I I G
E   D   H   N``````

``````def convert(self, s: str, numRows: int) -> str:
cur_return = []
if numRows > 2:
for row in range(0,numRows):
if row==0 or row==numRows-1:
for i in range(row,len(s),2*numRows-2):
cur_return.append(s[i])
else:
a = row
b = 2*numRows - row - 2
while a<len(s) or b<len(s):
if a < len(s):
cur_return.append(s[a])
a = a + 2*numRows - 2
if b < len(s):
cur_return.append(s[b])
b = b + 2*numRows - 2
else:
if numRows == 2:
cur_return.append(s[0::2])
cur_return.append(s[1::2])
if numRows == 1:
cur_return.append(s)
return ''.join(cur_return)``````

优质代码（python）：

``````class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""

if numRows == 1 or numRows >= len(s):
return s
L = [''] * numRows
index, step = 0, 1
for x in s:
L[index] += x
if index == 0:
step = 1
elif index == numRows - 1:
step = -1
index += step
return ''.join(L)``````

官方解答（java）：

``````class Solution {
public String convert(String s, int numRows) {

if (numRows == 1) return s;

StringBuilder ret = new StringBuilder();
int n = s.length();
int cycleLen = 2 * numRows - 2;

for (int i = 0; i < numRows; i++) {
for (int j = 0; j + i < n; j += cycleLen) {
ret.append(s.charAt(j + i));
if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
ret.append(s.charAt(j + cycleLen - i));
}
}
return ret.toString();
}
}``````

原文作者：Z字形编排问题
原文地址: https://blog.csdn.net/m0_38101326/article/details/87973792
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。