Z 字形变换

将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。算法

好比输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列以下:app

L   C   I   R
E T O E S I I G
E   D   H   N

以后,你的输出须要从左往右逐行读取,产生出一个新的字符串,好比:"LCIRETOESIIGEDHN"函数

请你实现这个将字符串进行指定行数变换的函数:spa

string convert(string s, int numRows);

示例 1:code

输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"

示例 2:blog

输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:

L     D     R
E   O E   I I
E C   I H   N
T     S     G

思路字符串

按照与逐行读取 Z 字形图案相同的顺序访问字符串。get

算法string

首先访问 行 0 中的全部字符,接着访问 行 1,而后 行 2,依此类推...io

解法一:

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1:
            return s
        n = len(s)
        ans = []
        step = 2 * numRows - 2
        for i in range(numRows):
            one = i
            two = -i
            while one < n or two < n:
                if 0 <= two < n and one != two and i != numRows - 1:
                    ans.append(s[two])
                if one < n:
                    ans.append(s[one])
                one += step
                two += step
        return "".join(ans)

解法二:

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)
相关文章
相关标签/搜索