此题为借鉴的别人的实现方法(实现思路上比较简单,重点在于找到一个高效且节省内存的实现手段…感慨一下大神还是真的很厉害的)
题目说明
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)
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P------I-------N
A—L-S—I–G
Y–A--H-R
P------I
代码部分
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
zig = [""] * numRows
loc = self.location(numRows-1)
#生成位置信息loc以便于后期list排单词的时候归位
for c, l in zip(s,loc):
zig[l] += c
#c即从s中一个单词一个单词的选择
#l用于控制每次用于放在list(zig)的哪个位置即从属于第几行的单词
return "".join(zig)
def location(self, bound):
index, inc = 0, 1
while True:
yield index;
#yield每次迭代输出next值,节省空间且避免反复调用
#本代码最大的亮点设计
if index == bound:
inc = -1
elif index == 0:
inc = 1
index = index + inc
Runtime: 76 ms, faster than 95.46% of Python3 online submissions for ZigZag Conversion.
Memory Usage: 12.5 MB, less than 88.94% of Python3 online submissions for ZigZag Conversion.
关于yield的用法可参考此篇文章,讲的非常简单易懂
https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/
主要思路:
以三行的z字型举例,现有一个S[‘abcdefghijk’]字符串,所以最后会以行为单位生成三个单词且最后单词拼接成为最后的输出;
第一个单词:a------e-------i
第二个单词:b–d—f---h—j
第三个单词:c------g-------k
很简单的看来就是s的单词依次出一个,光标指向从1行到2行到3行再到2行到1行重复循环往次(从这个角度考虑的话实现思路非常明确)