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"
.
首先明白题意,给出一个字符串,按照之字形(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 s 12 zigzag = [‘‘ for i in range(numRows)] # 初始化zigzag为[‘‘,‘‘,‘‘] 13 row = 0 # 当前的列数 14 step = 1 # 步数:控制数据的输入 15 for c in s: 16 if row == 0: 17 step = 1 18 if row == numRows - 1: 19 step = -1 20 zigzag[row] += c 21 row += step 22 return ‘‘.join(zigzag)
时间: 2024-10-13 23:55:42