LeetCode - ZigZag Conversion

LeetCode - ZigZag Conversion

The Problem is described as following:

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

My Solution is as following:

class Solution:
    # @return a string
    def convert(self, s, nRows):
        if s == '':
            return ''
        sr = ''
        length = len(s)
        if nRows == 1 or length <= nRows:
            return s
        for i in range(nRows):
            idx = i
            sr += s[idx]
            while True:
                if i != nRows-1:
                    idx += 2*(nRows-i-1)
                    if idx >= length:
                        break
                    sr += s[idx]
                if i != 0:
                    idx += 2*i
                    if idx >= length:
                        break
                    sr += s[idx]
        return sr     

本题比较简单,通过简单的数学分析就可以找到排列的规律,但要注意对一些特殊情况的判断。

你可能感兴趣的:(LeetCode)