6. ZigZag Conversion

解法一,计算出周期,推导出取余后的结果和index的关系。

    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if s == '' or numRows == 1 or len(s) <= numRows:
            return s

        res = [''] * numRows
        i = 0
        # 注意如果numRows等于1,此时T=0,对0取余会出问题,在最前面加一个numRows的判断
        T = 2 * numRows - 2
        for item in s:
            temp = i % T
            if temp >= numRows:
                temp = T - temp
            res[temp] += item
            i += 1
        final_res = ''
        for i in range(numRows):
            final_res += res[i]
        return final_res

解法二。while循环内部包含两个for循环。

    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if s == '' or numRows == 1 or len(s) <= numRows:
            return s

        res = [''] * numRows
        k = 0
        while k < len(s):
            for i in range(numRows-1):
                # 注意加条件判断
                if k < len(s):
                    res[i] += s[k]
                    k += 1
            for j in range(numRows-1,0, -1):
                if k < len(s):
                    res[j] += s[k]
                    k += 1
        final_res = ''
        for i in range(numRows):
            final_res += res[i]
        return final_res

你可能感兴趣的:(6. ZigZag Conversion)