https://leetcode.com/problems/zigzag-conversion/
思路1
其实这里只需要找出一般公式就行,没什么技巧。当i是1到n-2行时,第i行第一个在斜线上的元素在s中的index是 2 numRows - 2, 所以与第i行第一个元素 i (以及后面增加2 numRows - 2后的j),相差 2 numRows - 2 - 2 i个元素。
my code:
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if len(s) == 1 or numRows == 1:
return s
res = []
for i in xrange(numRows):
j = i
while j < len(s):
res.append(s[j])
if i >0 and i < numRows - 1:
tmp = j + 2*numRows - 2 - 2*i
if tmp < len(s):
res.append(s[tmp])
j += 2*numRows - 2
return "".join(res)
思路2
http://www.cnblogs.com/zuoyuan/p/3777745.html
其中index是tmp中哪一行的index,这个index的变化是0,1,2,..., nRow - 1, nRow(这个值已经是在斜线上的元素) ->转换成nRow - 2, nRow - 3, ..., 2, 1, 0, -1->转化成1,2,...
这里step就是1和-1,用来调整index的运动方向的
class Solution:
# @return a string
def convert(self, s, nRows):
if nRows==1: return s
tmp=['' for i in range(nRows)]
index=-1; step=1
for i in range(len(s)):
index+=step
if index==nRows:
index-=2; step=-1
elif index==-1:
index=1; step=1
tmp[index]+=s[i]
return ''.join(tmp)
思路3
直接把zigzag放到2Dmatrix里面,然后输出就行了。
http://yucoding.blogspot.hk/2013/02/leetcode-question-125-zigzag-conversion.html