首页 > 代码库 > 『LeetCode』练习第四弹_算法6题

『LeetCode』练习第四弹_算法6题

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 import copy
 2 class Solution(object):
 3     def convert(self, s, numRows):
 4         """
 5         :type s: str
 6         :type numRows: int
 7         :rtype: str
 8                 """
 9         def postion_next(x, y):
10 
11             if x == 0:
12                 return x + 1, y
13             elif x == r - 1:
14                 return x - 1, y + 1
15             elif mat[x - 1][y] ==  :
16                 return x - 1, y + 1
17             else:
18                 return x + 1, y
19 
20         r = numRows
21         if s == "":
22             return ""
23         if r == 1:
24             return s
25         c = (int(len(s) / (2 * r - 2)) + 1) * (r - 1)
26         line = []
27         mat = []
28         for i in range(c):
29             line.append( )
30         for i in range(r):
31             mat.append(copy.deepcopy(line))
32         l = len(s)
33         postion_s = 0
34         postion_m = [0, 0]
35         while True:
36             # print(postion_m)
37             if (postion_s) == l:
38                 break
39             mat[postion_m[0]][postion_m[1]] = s[postion_s]
40             postion_s += 1
41             postion_m = postion_next(postion_m[0], postion_m[1])
42 
43         # for i in range(r):
44         #     for j in range(c):
45         #         print(mat[i][j], end=‘‘)
46         #         if j == c - 1:
47         #             print(‘\n‘, end=‘‘)
48         res = []
49         for i in range(r):
50             res += mat[i]
51         res = ‘‘.join(res)
52         # print(‘‘.join(res.split(‘ ‘)))
53         return ‘‘.join(res.split( ))

结果:超时,不过逻辑没问题,注释部分是可视化输出z字形打印。

总结:

1.原生python矩阵生成操作好麻烦,用numpy的话np.array(list(‘ ‘*9)).reshape(3,3)就可以生成3*3的字符型矩阵

2.复习到了copy库的知识,如果不进行deepcopy的话下面的代码中mat的全部r层会浅拷贝line。

1 line = []
2 mat = []
3 for i in range(c):
4     line.append( )
5 for i in range(r):
6     mat.append(copy.deepcopy(line))

3.复习了str.split()的str切片剔除分隔符为list操作,顺便str.strip()开头结尾剥离操作,‘‘.join(list)列表合并为str操作。

『LeetCode』练习第四弹_算法6题