ZigZag Conversion
Question
P A H N
A P L S I I G
Y I Rstring convert(string text, int nRows);Answer
solution:
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
down = True
strings = ['' for i in range(numRows)] #产生二维数组
# go through the string and append letters one by one
lpos = 0
for letter in s:
strings[lpos] += letter #注意每行都是字符串,所以用字符串加运算
if lpos == numRows - 1:
lpos -= 1
down = False #如果到达最后一行,则停止下降
elif lpos == 0:
lpos = 1
down = True #如果到达第一行,则停止上升
elif down:
lpos += 1
else:
lpos -= 1
return ''.join(strings)Knowledge:
Last updated