美文网首页
06.leetcode题目讲解(Python):Z字形变换

06.leetcode题目讲解(Python):Z字形变换

作者: 夏山闻汐 | 来源:发表于2018-07-16 16:44 被阅读96次

    题目:


    image.png

    这个题我采用的是通过方向控制,来将字符串里的字符添加到构建的list中,在循环中的碰到最后一行或者第一行进行方向改变。需要考虑行数为 1 的特殊情况,这种情况下直接返回字符串。

    参考代码如下:

    class Solution:
        def convert(self, s, numRows):
            """
            :type s: str
            :type numRows: int
            :rtype: str
            """
            # no need to convert
            if numRows == 1:
                return(s)
    
            zlist = []
            sc = ""
            n = numRows
    
            # create null list
            while n:
                zlist.append([])
                n = n - 1
    
            j = 0
            for a in s:
                if j == 0:
                    # direction change
                    coverse = False
                zlist[j].append(a)
                if j + 1 < numRows:
                    if coverse:
                        j = j - 1
                    else:
                        j = j + 1
                else:
                    j = j - 1
                    # direction change
                    coverse = True
    
            # get the converted string
            for z in zlist:
                for t in z:
                    sc = sc + t
            return(sc)
    

    ps:如果您有好的建议,欢迎交流 :-D,也欢迎访问我的个人博客:tundrazone.com

    相关文章

      网友评论

          本文标题:06.leetcode题目讲解(Python):Z字形变换

          本文链接:https://www.haomeiwen.com/subject/uymbpftx.html