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:app
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".this
这个题目有两种作法:第一种是模拟,也就是说咱们能够有几行就开几个数组都存起来,最后合到一块儿就能够了;另外一种方法是找规律。由于第一种比较直观,故代码实现了第一种思路:code
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