6. Zigzag conversion

English Title: the string "paymailing" 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 legitimacy)

Chinese understanding is to give a string and a number, fill the string into the inverted Z-shaped input string, read the characters according to the column, get a new character, and output the character.

For example: string “paypalischiring”, 3

1 P   A   H   N
2 A P L S I I G
3 Y   I   R

My solution is to straighten the inverted Z-shape. It is not difficult to find that the number of lines corresponding to the string is 1232123… We need two variables, one is the index ‘I’, which is used to say that the corresponding character is added to the nth line, and the other is used to control the direction ‘n’. If it is less than the maximum number of lines, then n + 1, if it is equal to the maximum value, then change the direction n – = 1, Index I is added up until the whole string is filled.

My problem-solving code is as follows, there are many places to optimize, just to provide a general idea:

 1 class Solution(object):
 2     def convert(self, s, numRows):
 3         if numRows == 1:
 4             return s
 5         ldict = {}
 6         for i in range(1,numRows+1):
 7             ldict[i] = ''
 8         n = 1
 9         i = 0
10         while i < len(s):
11             while n < numRows:
12                 if i == len(s):
13                     break
14                 ldict[n] += s[i]
15                 n +=1
16                 i +=1
17             while n &> 1:
18                 if i == len(s):
19                     break
20                 ldict[n] += s[i]
21                 n -= 1
22                 i += 1
23         out = ''
24         for i in ldict.values():
25             out +=i 
26         return out

Similar Posts: