将字符串 "PAYPALISHIRING"
以Z字形排列成给定的行数:
P A H N A P L S I I G Y I R
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
实现一个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR"
示例 2:
输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释: P I N A L S I G Y A H R P I
这道题研究了很多,出现很多问题,尤其是在分析的过程中看了很多其他博主的分析,最终还是觉得这一个的分析比较经典
https://www.cnblogs.com/TenosDoIt/p/3738693.html
最重要的分析出来不是第一行和不是最后一行的数字之间的位置关系。
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
length = len(s)
interval = 2*numRows - 2
result = ''
for i in range(0, length, interval):
result += s[i]
for i in range(1, numRows-1):
inter = 2*i
j = i
while j < len(s):
result += s[j]
inter = interval - inter
j += inter
for i in range(numRows-1, length, interval):
result += s[i]
return result