将字符串 "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
"""方法一"""
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if 1 == numRows:
return s
len_s = len(s)
piece_len = 2 * (numRows - 1)
result = ""
index = 0
while index < len_s:
result += s[index]
index += piece_len
for m in range(1, numRows - 1):
index = m
while index < len_s:
result += s[index]
right_index = index + (numRows - m - 1) * 2
if right_index < len_s:
result += s[right_index]
index += piece_len
index = numRows - 1
while index < len_s:
result += s[index]
index += piece_len
return result
"""方法二"""
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
# 若行数为1,直接输出即可
if numRows == 1:
return s
# resultlist为结果的列表形式
resultlist = []
gap = 2 * numRows - 2
# 用嵌套循环完成计算
for i in range(0, numRows):
temp1 = i
temp2 = gap - i
# 分两种情况,情况1:第0行和第numRows行。temp1为主列的循环
if temp1 == 0 or temp1 == numRows - 1:
while temp1 < len(s):
resultlist.append(s[temp1])
temp1 = temp1 + gap
# 情况二:除首尾行外的其他行。temp1为主列的循环,temp2为插入元素的循环
else:
while temp1 < len(s):
resultlist.append(s[temp1])
temp1 = temp1 + gap
if temp2 < len(s):
resultlist.append(s[temp2])
temp2 = temp2 + gap
# resultst为未最终返回结果字符串结果
resultstr = ''.join(resultlist)
return resultstr