首页 > 代码库 > leetcode6:Zigzag Conversion@Python

leetcode6:Zigzag Conversion@Python

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   NA P L S I I GY   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".

 

首先明白题意,给出一个字符串,按照之字形(Zigzag)排列成矩形,将矩阵每一行连接起来构成一个字符串。

技术分享

将矩阵压缩得到:

技术分享

 

 1 #-*-coding:utf-8-*- 2  3 class Solution(object): 4     def convert(self, s, numRows): 5         """ 6         :type s: str 7         :type numRows: int 8         :rtype: str 9         """10         if numRows == 1:11             return s12         zigzag = [‘‘ for i in range(numRows)]  # 初始化zigzag为[‘‘,‘‘,‘‘]13         row = 0                                # 当前的列数14         step = 1                               # 步数:控制数据的输入15         for c in s:16             if row == 0:17                 step = 118             if row == numRows - 1:19                 step = -120             zigzag[row] += c21             row += step22         return ‘‘.join(zigzag)

 

leetcode6:Zigzag Conversion@Python