Z 字形变换

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:

L   C   I   R
E T O E S I I G
E D H N

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"

示例 2:

输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释: L D R
E O E I I
E C I H N
T S G

思路

按照与逐行读取 Z 字形图案相同的顺序访问字符串。

算法

首先访问 行 0 中的所有字符,接着访问 行 1,然后 行 2,依此类推...

解法一:

class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows <= 1:
return s
n = len(s)
ans = []
step = 2 * numRows - 2
for i in range(numRows):
one = i
two = -i
while one < n or two < n:
if 0 <= two < n and one != two and i != numRows - 1:
ans.append(s[two])
if one < n:
ans.append(s[one])
one += step
two += step
return "".join(ans)

解法二:

class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
# no need to convert
if numRows == 1:
return(s) zlist = []
sc = ""
n = numRows # create null list
while n:
zlist.append([])
n = n - 1 j = 0
for a in s:
if j == 0:
# direction change
coverse = False
zlist[j].append(a)
if j + 1 < numRows:
if coverse:
j = j - 1
else:
j = j + 1
else:
j = j - 1
# direction change
coverse = True # get the converted string
for z in zlist:
for t in z:
sc = sc + t
return(sc)
上一篇:HDU 5745 La Vie en rose 暴力


下一篇:C#常用的内置委托