题目:
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R E T O E S I I G E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
示例:
输入: s = "LEETCODEISHIRING", numRows = 3 输出: "LCIRETOESIIGEDHN"
输入: s = "LEETCODEISHIRING", numRows = 4 输出: "LDREOEIIECIHNTSG"
解释: L D R E O E I I E C I H N T S G
首先看到z字形的规律,可以通过索引、切片等操作直接取得对应行的所有字符,与答案的按行访问相同。
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if len(s) <= 2 or numRows == 1:
return s
new_s = ""
cycle = numRows + numRows - 2
for i in range(numRows):
if (i == 0) or (i == numRows - 1):
new_s += s[i::cycle]
else:
for j in range(i, len(s), cycle):
new_s += s[j: j + cycle - i - i + 1: cycle - i - i]
return new_s
复杂度分析:
时间复杂度:,最糟糕的情况就是遍历每个字符。
空间复杂度:
答案的按行排序,遍历每个字符,每个字符都可以加入到对应行中,行号加减在z字形头尾处改变。
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if len(s) <= 2 or numRows == 1:
return s
row_list = [""] * numRows
row = 0
is_down = True
for i in range(len(s)):
row_list[row] += s[i]
if is_down:
row += 1
if row == numRows - 1:
is_down = False
else:
row -= 1
if row == 0:
is_down = True
return "".join(row_list)
复杂度分析:
时间复杂度:,遍历每个字符。
空间复杂度: