1. 程式人生 > >2018暑假第十題

2018暑假第十題

題目:

將字串 "PAYPALISHIRING" 以Z字形排列成給定的行數:   (python)

P   A   H   N
A P L S I I G
Y   I   R

之後從左往右,逐行讀取字元:"PAHNAPLSIIGYIR"

實現一個將字串進行指定行數變換的函式:

string convert(string s, int numRows);

示例 1:

輸入: s = "PAYPALISHIRING", numRows = 3
輸出: "PAHNAPLSIIGYIR"

示例 2:

輸入:
s = "PAYPALISHIRING", numRows = 4 輸出: "PINALSIGYAHRPI" 解釋: P I N A L S I G Y A H R P I

題目連結:https://leetcode-cn.com/problems/zigzag-conversion/description/

答案:

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