有人可以给我解释一下代码zigZag问题吗?
将字符串“ PAYPALISHIRING”以Z字形写在给定数量的行上,如下所示:(您可能希望以固定字体显示此图案以提高可读性)
P A H N
A P L S I I G
Y I R
然后逐行读取:“ PAHNAPLSIIGYIR”
编写代码,该代码将采用字符串并在给定行数的情况下进行此转换:
string convert(string s,int numRows);
输入:s =“ PAYPALISHIRING”,numRows = 3 输出:“ PAHNAPLSIIGYIR”
输入:s =“ PAYPALISHIRING”,numRows = 4 输出:“ PINALSIGYAHRPI” 说明:
P I N
A L S I G
Y A H R
P I
我不是在寻找任何人来解决它。请帮助我理解问题。
答案 0 :(得分:0)
def convert(self, s: str, numRows: int) -> str:
#
if numRows <2 or len(s)<numRows: return s
n = numRows-1
step = n*2
res = s[::step]
for i in range(1,n):
for v,w in itertools.zip_longest(s[i::step],s[step-i::step],fillvalue=''):
res += v+w
return res + s[n::step]
或者不使用lib。 (类似的想法)
def convert(self, s, numRows):
step = (numRows == 1) - 1 # 0 or -1
rows, idx = [''] * numRows, 0
for c in s:
rows[idx] += c
if idx == 0 or idx == numRows-1:
step = -step #change direction
idx += step
return ''.join(rows)