题目链接:
https://leetcode.com/problems/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 RAnd 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型数据,规律十分明显,不详述,很显然,该方法简单,但是效率也不高。
耗时:717ms。
class Solution:
# @return a string
def convert(self, s, nRows):
if not s or nRows<=1:
return s
sList = []
j = 0
i = 0
while (i<len(s)):
Temp = ['']*nRows
if j%(nRows-1) == 0:
k=0
while (k<nRows and i < len(s)):
Temp[k] = s[i]
k += 1
i += 1
else:
k = j%(nRows-1)
Temp[-k-1] = s[i]
i += 1
sList.append(Temp)
j += 1
res = ''
for i in range(len(sList[0])):
for j in range(len(sList)):
if sList[j][i]:
res += sList[j][i]
return res