原题目:
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like
this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line:
"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should
return "PAHNAPLSIIGYIR".
题目的意思是说将字符 一个个 按照 纵向 从上到下再从下到上,如此反复排列。然后让我们按行来拼接它们。
Demo1 (3行)
| 1 | 5 | |
| 2 | 4 | 6 |
| 3 | 7 |
Demo2 (4行)
| 1 | 7 | |
| 2 | 6 | 8 |
| 3 | 5 | 9 |
| 4 | 10 |
Demo3 (5行)
| 1 | 9 | |
| 2 | 8 | 10 |
| 3 | 7 | 11 |
| 4 | 6 | 12 |
| 5 | 13 |
我们看完上面3个例子,不难发现 奇数列的间隔分别是:4 , 6 , 8。而我们三个Demo的行数是:3,4,5. 那么不然得出。 奇数列间隔 = 2*行数 - 2;
那么看偶数列间隔,偶数列有个特点是不包含在 首行和末尾行的,所以在推算的时候要排除掉。
拿Demo3 为例: 第二列比第一列的差依次为:6,4,2.
那么不难看出:偶数列间隔 = 奇数列间隔 - 行数*2
OK,那么代码就好写了:
class Solution(object):
def convert(self, s, numRows):
if len(s)>0 and numRows >1:
row = 0
offset = 2*numRows -2
result = ''
while row < numRows:
col = row
while col < len(s):
result += s[col]
if row!=0 and row != numRows-1:
index =col + offset - 2* row
if index < len(s):
result += s[index]
col += offset
row +=1
return result
else:
return s
本文介绍了一种将字符串以Z形方式分布并按行读取的算法实现。通过实例展示了不同行数下字符串的分布规律,并给出了Python代码实现。
287

被折叠的 条评论
为什么被折叠?



