昨天和她的父亲聊天的时候,他直接问我:你最近同我女儿联系否?这着实是把我弄得一愣一愣的,哈哈哈哈,到今天想想也是蛮有趣的。
这一题官方给的解题方法是按行排序和按行访问两种方法,好肯定是很好的,但我还是想先把我第一次的方法给贴出来,因为我觉得这个可能对我们这些菜鸟会更容易接受些(大神绕道)
方法一:得出Z字型矩阵
这个方法就很直接了,题目不是要我们求出一个字符串Z字型变换嘛,那我们就先把它的Z字型矩阵求出来,再依次按行读取相应元素即可得出最终答案,是不是很简单。
代码如下:
class Solution:
def convert(self, s, numRows):
if numRows <= 1:
return s
DecArray = self.getArray(s, numRows)
result = ''.join(DecArray.flatten())
result = result.replace('-', '')
return result
# 构建Z型数组法获得相关数组
def getArray(self, s, numRows):
DecArray = np.array([['-'] * len(s)] * numRows)
ArrayIndex = 0
IndexCol = 0
while ArrayIndex < len(s):
if IndexCol % (numRows - 1) == 0:
line = ArrayIndex - (2 * numRows - 2) * int(IndexCol / (numRows - 1))
if line < numRows:
DecArray[line][IndexCol] = s[ArrayIndex]
else:
IndexCol += 1
ArrayIndex -= 1
else:
sum = int(IndexCol / (numRows - 1) + 1) * (numRows - 1)
line = sum - IndexCol
DecArray[line][IndexCol] = s[ArrayIndex]
IndexCol += 1
ArrayIndex += 1
return DecArray
但是这个最简单的方法的执行效率也真是不咋地,硬是没跑出来,报了超出时间限制的错误。当时确实是对我有些打击,觉得没有哪块地方要花费很长时间,想来想去最后用了官方给的方法才得出答案,还是有些不爽的。
方法二:按行排序法
思路
通过从左向右迭代字符串,我们可以轻松地确定字符位于 Z 字形图案中的哪一行。
算法
我们可以使用 \text{min}( \text{numRows}, \text{len}(s))min(numRows,len(s)) 个列表来表示 Z 字形图案中的非空行。
扫描二维码关注公众号,回复:
4140394 查看本文章
从左到右迭代 ss,将每个字符添加到合适的行。可以使用当前行和当前方向这两个变量对合适的行进行跟踪。
只有当我们向上移动到最上面的行或向下移动到最下面的行时,当前方向才会发生改变。
代码如下:
class Solution:
def convert(self, s, numRows):
if numRows <= 1:
return s
DecDict = self.getArray(s, numRows)
rows = min(len(s), numRows)
ListStr = []
for line in range(rows):
ListStr.extend(DecDict[line])
return ''.join(ListStr)
# 按行排序法获得相关数组
def getArray(self, s, numRows):
rows = min(len(s), numRows)
DecDict = {}
for row in range(rows):
DecDict[row] = []
curRow = 0
goingDown = False
for index in range(len(s)):
DecDict[curRow].extend(s[index])
if curRow == 0 or curRow == numRows - 1:
goingDown = not goingDown
curRow += 1 if goingDown else -1
return DecDict
这个方法是真的香啊!!!哈哈哈哈,真的受启发了,但执行效率也是惨不忍睹,不过能通过就行了。