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字行排列,然後按每行順序輸出所有字母~這種題主要是找出規律來~
class Solution:
# @return a string
def convert(self, s, nRows):
if s is None or len(s) == 0 or nRows <= 0: return ""
if nRows == 1: return s
step = 2 * nRows - 2; res = ""
for i in xrange(nRows):
for j in xrange(i, len(s), step):
res += s[j]
if i > 0 and i < nRows - 1 and j + step - 2 * i < len(s):
res += s[j + step - 2 * i]
return res