1. 程式人生 > >ZigZag Conversion

ZigZag Conversion

sof num 這一 solution nap return lsi bject should

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".

分析:

  這道題主要是找規律。

方法一:

  比較直觀的解法,使用list存儲每一行,最後拼接。

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        
""" res = [‘‘]*numRows step = 1 row = 0 if len(s) <= 2 or numRows <= 1: return s for i in range(len(s)): res[row] += s[i] row += step if row >=numRows: row = numRows-2 step
= -1 if row < 0: row = 1 step = 1 ans = ‘‘ for i in range(len(res)): ans += res[i] return ans

方法二:

  發現所有行的重復周期都是 2 * nRows - 2,對於首行和末行之間的行,還會額外重復一次,重復的這一次距離本周期起始字符的距離是 2 * nRows - 2 - 2 * i

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if len(s) < 2 or numRows < 2:
            return s
        jump = 2*(numRows-1)
        res = ‘‘
        for i in range(numRows):
            j = i
            while j < len(s):
                res += s[j]
                if i > 0 and i < numRows-1 and j+jump-2*i < len(s):
                    res += s[j+jump-2*i]
                j += jump
        return res

ZigZag Conversion