@author: ZZQ
@software: PyCharm
@file: convert.py
@time: 2018/9/20 20:12
要求: Z字形变换
将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
P A H N
A P L S I I G
Y I R
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
实现一个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
e.g.:
输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"
输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
思路: 建一个有numRows个字符串的列表,一个循环写两次列表,一次顺着写,一次反着写,注意下标变化。
class Solution():
def __init__(self):
pass
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
s_len = len(s)
zlist = []
for i in range(numRows):
sub_list = ""
zlist.append(sub_list)
k = 0
time = 0
while k < s_len:
if time == 0:
list_index = 0
while list_index < numRows:
if k < s_len:
zlist[list_index] += s[k]
else:
break
k += 1
list_index += 1
time += 1
else:
list_index = 1
while list_index < numRows:
if k < s_len:
zlist[list_index] += s[k]
else:
break
k += 1
list_index += 1
list_index -= 1
while list_index > 0:
list_index -= 1
if k < s_len:
zlist[list_index] += s[k]
else:
break
k += 1
time += 1
z_str = ""
for sub_str in zlist:
z_str += sub_str
return z_str
if __name__ == "__main__":
answer = Solution()
print answer.convert(s="ABJHFSDKAGFSLABVSJDK", numRows=2)