Z字形变换

将字符串 "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

 1 class Solution(object):
 2     def convert(self,s,numRows):
 3         '''
 4 
 5         :type s:str
 6         :type numRows:int
 7         :rtype:str
 8         '''
 9         if numRows==1 or numRows >= len(s):
10             return s
11         L=['']*numRows #建立长度为num的空列表
12         index,step=0,1
13         for x in s:
14             L[index] += x
15             if index == 0:
16                 step=1
17             elif index==numRows-1:
18                 step=-1
19             index += step
20         return ''.join(L)
21 
22 s='PAYPALISHIRING'
23 str=Solution.convert(1,s,3)
24 print(str)

 

posted @ 2018-07-08 18:09  我们都是大好青年  阅读(992)  评论(0编辑  收藏  举报