首页 > 代码库 > [LeetCode #6] ZigZag Conversion

[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   NA P L S I I GY   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 s10         11         ret = ""        12         inc = 2 * (numRows - 1)13         14         for i in range(numRows):15             j = i16             d1 = (numRows - i  -1) * 217             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 ret26             

 

[LeetCode #6] ZigZag Conversion