思路一
呜呜呜我想了半天,左右打补丁结果还是到处漏风wwwT^T,还是贴上来记录下,原因是没有考虑下面这种情况
我的思路有点像这个,6. Z 字形变换 找规律解决,附详细代码介绍
class Solution:
def convert(self, s: str, numRows: int) -> str:
if len(s) == 1 or numRows == 1 or len(s) <= numRows:
return s
res = [] # to avoid creating the futile string, update it until the ending
reslist = [] # first record the index of the result
Kthnumber = 0 # record the current index
r, c = 0, 0 # record the circle number
base = 0 # record the number of the first row as the basis
i = 0
# get the first row as the basis
print('lens', len(s))
while True:
Kthnumber = r * (2 * numRows - 2) + 1 # th
print(Kthnumber)
if Kthnumber > len(s):
break
reslist.append(Kthnumber - 1) # update the index
base += 1
r += 1
print(reslist)
print('base', base)
# seemingly, base, r have the identical meaning
# like binary tree
print('numRows', numRows)
while True: # cow
c += 1
print(c)
if c == numRows:
break
while True:
Kthnumber = reslist[i]
i += 1
right = Kthnumber + c
left = Kthnumber - c
if c < numRows - 1: # in the last cow, avoid the duplicate , so only record the right
if left >= 0: reslist.append(left)
if right < len(s): reslist.append(right)
if i == base :
i = 0
break
# convert index to str
for i in reslist:
res.append(s[i])
print(''.join(res))
# assert "PAHNAPLSIIGYIR" == ''.join(res)
return ''.join(res)
思路二
看了其他解析,才发觉许多精妙之处,细节可看Z 字形变换(清晰图解)
class Solution:
def convert(self, s: str, numRows: int) -> str:
if len(s) == 1 or numRows == 1: # 特殊情况
return s
res = [[] for _ in range(numRows)] # 每一行一个list
i = 0
flag = -1
for char in s: # 遍历字符串,行方向移动res数组,接收字符
res[i].append(char)
if i == numRows - 1 or i == 0: flag = -flag # Z型转弯角,换移动方向
i += flag
# 汇总1
for i in range(numRows):
res[i] = "".join(res[i])
# 汇总2
return "".join(res)
让我想到了单摆沙漏,底下纸以垂直方向匀速运动,可成正弦运动形状。
换个思维,移动参照物,效果更佳。