LeetCode算法题python解法: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)

中文理解大概就是给定一个字符串和一个数字,将字符串填入倒Z形输入字符串,然后按照列读取字符,得到一个新的字符,输出这个字符。

例如:字符串"PAYPALISHIRING",3

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

我的解题思路把这个倒Z型拉直,不难发现字符串对应的行数分别是1232123.......,我们需要两个变量,一个索引‘’ i‘’ ,用来讲对应字符添加到第n行,还有一个用来控制方向 ‘’n‘’,小于 行数最大值则n+1,等于最大值时则换个方向 n -= 1,索引 i 则一直往上加,直到取满整个字符串。

我的解题代码如下,有很多地方可以优化,只是提供大概思路:

 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 

 

posted @ 2018-08-23 17:02  slarker  阅读(722)  评论(0编辑  收藏  举报