找规律
等差数列的首项和公差
第一行为首项是0,公差是2(n-1)的等差数列
中间是两个等差数列交错
最后一行是首项是n-1,公差是2(n-1)的等差数列
class Solution:
def convert(self, s: str, n: int) -> str:
if n == 1: return s # n是输出的行数
res = ''
for i in range(n):
if not i or i == n - 1: # 当前是第一行或者最后一行时
j = i
while j < len(s):
res += s[j]
j += 2 * (n - 1)
else: # 当前行是中间行,有两个交错的等差数列
j = i; k = 2 * (n - 1) - i # j,k分别是前后等差数列的值
while j < len(s) or k < len(s):
if j < len(s): res += s[j]
if k < len(s): res += s[k]
j += 2 * (n - 1)
k += 2 * (n - 1)
return res