LeetCode Medium: 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 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".
“Z”形转换,意思就是将一行字符串按行数竖着写,然后“Z”形折回,写第二竖列,依次循环,然后按行写出最后结果,如下:
numRows = 3时: numRows = 3时:
“PAHNAPLSIIGYIR”
“PHASIYIRPLIGAH”
二、思路
本题是一个找规律的题,很显然我并没有找出来,刚拿到题我并没有任何思路,参考了别人的博客才发现了循环和规律,最后的博客给了详细的解释,我这里就不重复了,这道题找出规律是重点,找到规律之后很简单,两层循环,外循环控制numRows,内循环控制每一行打印的字符。博客中的代码使用JAVA写的,我这里的思路跟其完全一样,只是换成Python写,想详细了解解题思路的可以参考后面博客。
三、代码
#coding:utf-8
'PAYPALISHIRING'
def convert(s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows <= 1:
return s
sb = ''
cycle = 2*numRows - 2 #numRows=3,cycle=4;numRows=5,cycle=8
for i in range(numRows):
for j in range(i,len(s),cycle):
sb = sb + s[j]
secondJ = j - i +cycle-i
if i != 0 and i != numRows - 1 and secondJ < len(s):
sb = sb + s[secondJ]
print(sb + str(len(sb)))
print(s + str(len(s)))
return sb
if __name__ == '__main__':
s = 'PAYPALISHIRING'
convert(s,3)
参考博客:https://www.cnblogs.com/lupx/archive/2015/09/14/leetcode-6.html
浙公网安备 33010602011771号