1. 程式人生 > >將字符串中的字符按Z字形排列,按行輸出

將字符串中的字符按Z字形排列,按行輸出

output alt == nap self 字符串 for sel str

示例1:

  Input: s = "PAYPALISHIRING", numRows = 3

技術分享圖片

  Output: "PAHNAPLSIIGYIR"

示例2:

技術分享圖片

解決方案:

    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if len(s) <= numRows or numRows==1 :
            
return s s_dict = {i:"" for i in range(numRows)} unit = 2*numRows - 2 for i in range(len(s)): remain = i%unit if remain <= numRows - 1: s_dict[remain] += s[i] else: pos = unit - remain s_dict[pos]
+= s[i] out = "" for i in range(numRows): out += s_dict[i] return out

將字符串中的字符按Z字形排列,按行輸出