题目简述
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".
解题思路:
这个题目有两种做法:第一种是模拟,也就是说我们可以有几行就开几个数组都存起来,最后合到一起就可以了;另一种方法是找规律。因为第一种比较直观,故代码实现了第一种思路:
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows == 1:
return s
gap = nRows - 2
res = []
for i in range(nRows):
res.append([])
i = 0
while i < len(s):
for j in range(nRows):
if i >= len(s):
break
res[j] += s[i]
i += 1
for j in range(gap,0,-1):
if i >= len(s):
break
res[j] += s[i]
i += 1
ress = ""
for i in res:
for j in i:
ress += j
return ress