将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。比如输入字符串为 "LEETCODEISHIRING"
行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"
。
我的垃圾代码(python):
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();
}
}