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
“.
https://leetcode.com/problems/zigzag-conversion/
n=2时,字符串坐标变成zigzag的走法就是:
0 2 4 6
1 3 5 7
n=3时的走法是:
0 4 8
1 3 5 7 9
2 6 10
n=4时的走法是:
0 6 12
1 5 7 11 13
2 4 8 10 14
3 9 15
观察坐标变化 第一行和最后一行,相邻行的坐标差都是
2n-2
,其他行坐标j+(2n-2)-2i
,以行遍历
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if (len(s)==0 or numRows <=0):
return ''
if numRows == 1:
return s
ret = []
size = 2*numRows-2
for i in range(0,numRows):
for j in range(i,len(s),size):
ret.append(s[j])
if (i!=0 and i!=numRows-1):
temp = j + size -2*i
if temp<len(s):
ret.append(s[temp])
return ''.join(ret)
既然用python做,那么应该很少代码才对,利用
list[-1]
list[-2]
的特性
ABCDEFG
A E
BD
C F
# n=3 将空格出压缩到下面形式
AE
BDG
CF
换个形式看上面的”压缩”后的结果
result[1]=AE
result[2]=BDG
result[3]=CF
然后 AE
+BDG
+CF
,这样就得到最后结果了。~
class Solution(object):
def convert(self, s, numRows):
result = [""] * (numRows + 1) #保存每一行的结果
level, order = 1, 1 # order指示是否逆序
for i in s:
result[level*order] += i #对应行加入字母
level += 1
if level >= numRows: # 判断是否应该逆序
level, order = 1, order * (-1)
return "".join(result)