C/C++教程

leetcode6. Z 字形变换

本文主要是介绍leetcode6. Z 字形变换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

题目描述:

https://leetcode-cn.com/problems/zigzag-conversion/

题解:

1.超时版

<1>定义一个shapez数组,大小为numRows*len(s),初始为全0

<2>从字符串s第一个元素开始写入shapez

<3>利用row col down right确定位置,将s[i]写入numRows[row][col],然后更新row=row+down col=col+right

<4>处理特殊情况:如果当前row=numRows-1  down=-1 right=1,向右上移动,如果row==0 down=1 right=0,重新开始向下移动

<5>读取shapez,将非0元素写入res

class Solution(object):

    def convert(self, s, numRows):

        if numRows==1:

            return s

        lens = len(s)

        shapez = [[0 for m in range(lens)] for n in range(numRows)]

        col = 0

        row = -1

        right = 0

        down = 1

        for i in range(lens):

            row = row+down

            col = col+right

            shapez[row][col] = s[i]

            if row == numRows-1:

                down = -1

                right = 1

            if row == 0:

                down = 1

                right = 0

        print(shapez)

        res = ""

        for i in range(numRows):

            for j in range(lens):

                if shapez[i][j]!=0:

                    res = res+shapez[i][j]

        return res

2.改进版

直接将shapez定义为字符串

def convert(self, s, numRows):
    if numRows==1:
        return s
    lens = len(s)
    shapez = [""] *numRows
    row = -1
    down = 1
    for i in range(lens):
        row = row+down

        shapez[row] = shapez[row]+s[i]
        if row == numRows-1:
            down = -1

        if row == 0:
            down = 1
    res = ""
    for i in range(numRows):
        res = res+shapez[i]
    return res

 

这篇关于leetcode6. Z 字形变换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!