首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。