【LeetCode】6. ZigZag Conversion解題報告(Python)


問題解決の考え方:
このテーマの目的は文字列を1つの字型に並べることであり、文字列を縦に並べ、1列が長い列が短い列、長い列がnumRowsが短い列がnumRows-2である.したがって、各行の文字を1つの配列で格納し、現在アクセスしている行を変数rowで記録し、文字列sの文字を順番に異なる行に入れ、すべての行の文字列を直列に接続する.
コードの説明:
1、zigzag=['for i in range(numRows)]はnumRows個を'とする配列を生成することを表す.
2、rowは行数を表し、stepは次のステップが上へ行くか下へ行くかを示すフラグです.if row==0:step=1 if row==numRows-1:step=-1は最初の行まで下に進み、最後の行まで歩いて上に進みます.
3、''.join((zigzag))はzigzagの配列を組み合わせることを表す
テストコード:
class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1:
            return s
        zigzag = ['' for i in range(numRows)]
        row = 0
        step = 1
        for c in s:
            if row == 0:
                step = 1
            if row == numRows - 1:
                step = -1
            zigzag[row] += c
            row += step
        return ''.join((zigzag))

s = '0123456789abcdef'
numRows = 4
print(Solution().convert(s, numRows))    #        

 
ブログ参照