[LeetCode #6] ZigZag Conversion

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   R

And 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".

 1 class Solution(object):
 2     def convert(self, s, numRows):
 3         """
 4         :type s: str
 5         :type numRows: int
 6         :rtype: str
 7         """
 8         
 9         if numRows < 2: return s
10         
11         ret = ""        
12         inc = 2 * (numRows - 1)
13         
14         for i in range(numRows):
15             j = i
16             d1 = (numRows - i  -1) * 2
17             
18             while (j < len(s)):
19                 ret += s[j] # js are the backbone columns, 
20                             # for n = 5, j are 0, 8, 16, ...
21                 if d1 != 0 and d1 != inc and (j + d1) < len(s):
22                     ret += s[j+d1]
23                 j += inc    
24                 
25         return ret
26             
原文地址:https://www.cnblogs.com/amadis/p/5925630.html