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)
相關文章
相關標籤/搜索