首页 > 代码库 > [LeetCode #6] ZigZag Conversion
[LeetCode #6] ZigZag Conversion
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"
.
1 class Solution(object): 2 def convert(self, s, numRows): 3 """ 4 :type s: str 5 :type numRows: int 6 :rtype: str 7 """ 8 9 if numRows < 2: return s10 11 ret = "" 12 inc = 2 * (numRows - 1)13 14 for i in range(numRows):15 j = i16 d1 = (numRows - i -1) * 217 18 while (j < len(s)):19 ret += s[j] # js are the backbone columns, 20 # for n = 5, j are 0, 8, 16, ...21 if d1 != 0 and d1 != inc and (j + d1) < len(s):22 ret += s[j+d1]23 j += inc 24 25 return ret26
[LeetCode #6] ZigZag Conversion
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。