6. ZigZag Conversion [easy] (Python)


タイトルリンク
https://leetcode.com/problems/zigzag-conversion/
タイトル
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: “PAHNAPLSIIGYIR” Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows); convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
タイトル翻訳
zigzag文字列変換、具体的な規則はテーマの原文を見て、長すぎて翻訳しません...書く関数は2つのパラメータを受け取り、変換する文字列textとzigzagの行数nRowsは、変換された文字列を返します.
考え方
考え方1
zigzag文字列を書く過程をシミュレートします.numRows個の要素を持つ配列を定義し、各要素は最初は空の文字列であり、numRows個の行文字列の初期状況を表す.次に、入力文字列sをスキャンし、各文字を対応する行文字列の末尾に順次追加する.最後に、すべての行文字列をつなぎ合わせると結果が得られます.注意、コードには型取り操作でzigzag文字を別の方向に書く必要があるかどうかを判断します.
コード#コード#
class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1 or numRows >= len(s):
            return s
        arr = [''] * numRows
        line, step = 0, -1
        for c in s:
            arr[line] += c
            if line % (numRows-1) == 0:
                step = - step
            line += step
        return ''.join(arr)

考え方2
数学的な点を少し考慮すると、sのi番目の文字(下付きは0番目から)がzigzagで書かれたように表示される行数が(行数0からnumRows-1行):i%(2*numRows-2)、if i%(2*numRows-2)=numRowsである場合、この結果が得られます.任意の位置の文字については、何行目にあるべきか知っています.次のコードは依然として元の文字列sを順次スキャンしているので、もちろん別の方法もあります.
コード#コード#
class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows <= 1 or numRows >= len(s):
            return s
        arr = [''] * numRows
        for i in xrange(len(s)):
            tmp = i % (numRows + numRows - 2)
            if tmp < numRows:
                arr[tmp] += s[i]
            else:
                arr[numRows + numRows - 2 - tmp] += s[i]
        return ''.join(arr)

PS:初心者はLeetCodeをブラシして、初心者はブログを書いて、書き間違えたり書いたりして、まだ指摘してください.ありがとうございます.転載は以下のことを明記してください.http://blog.csdn.net/coder_orz/article/details/52039689