6. Z 字形变换
题目:
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。
解法一:
以s = ‘leetcod’ , numRows = 3为例
res[0] = l c
res[1] = e t o
res[2] = e d
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows < 2 or numRows >= len(s): # 行数小于2不会形成z字形,行数大于字符串长度字符串只能成纵向排列且只有一列
return s
res = ["" for i in range(numRows)] # 列表生成器,生成与行数个数对应的空字符串
i,flag = 0,-1 # 初始化i,flag
for c in s: # 遍历整个字符串
res[i] += c # 将遍历到的字符存入生成的空字符串中
if i == 0 or i == numRows-1: # 判定是否已经到行头与行尾,如果是则反转,倒序往相应的字符串中添加字符
flag = - flag
i += flag
return "".join(res) # 字符串合成,并返回
解法二:
def convert(s,numRows):
# cache 生成行数的列表例如以numRows = 3为例:
# 然后整合成列表cache = [0,1,2,1]
"""
0 0
1 1 1
2
"""
cache = [i for i in range(numRows)] + [i for i in range(1,numRows - 1)][::-1]
# 按行对应字符串,并分别将每行的字符串保存到列表中
res = ['' for _ in range(numRows)]
for i ,c in enumerate(s):
# i%len的数对应cache中元素的下标,而cache中的元素又对应行数
res[cache[i%len(cache)]] += c
return ''.join(res)