您的位置:首页 > 其它

LeetCode No.6 Z 字形变换

2019-04-01 21:56 148 查看

LeetCode No.6 Z 字形变换


简述思路:额,题意理解了。不过。对于这个Z字型,有点茫然。怎么做出来呢。想法是,可能Z字只是噱头。关键在于。行数与中间字母的关系。3行。有一个单排字母。4行有两排。以此类推。
大体思路是对的。细节实现,还需要提升。问题在于,算法具体化实现,逻辑问题。解题时间还需要加强。总觉得太难了。就不想思考。用了太长时间了。需要定时定量。完成任务。

解题思路:不需要暴力遍历所有代码。首先找规律,首行,和末尾一行。排除特殊情况。(空行,单字符串,单行)然后就是分情况讨论。关键问题所在,就是限制。垂直行。这个应该算是数学方式。斜边上的数,用node_length - i 来推论。j = i + node_length。

class Solution:
def convert(self, s: 'str', numRows: 'int') -> 'str':
str_length = len(s)
node_length = 2*numRows - 2
result = ""
if str_length == 0 or numRows == 0 or numRows == 1:
return s
for i in range(numRows):
for j in range(i,str_length, node_length):
#包括的是首行,尾行,垂直行。
result += s[j]
#排除垂直行,注意范围限定!
if i != 0 and i != numRows - 1 and j - 2*i + node_length < str_length:
result += s[j-2*i+node_length]
return result
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: