這一題沒有什麼難度,主要就是找規律,Zigzag的含義網上有例子講的很明白。
我參考的思路來自這篇文章。
http://blog.csdn.net/cshaxu/article/details/12507201。
主要思路很簡單:
所有行每一個元素index的下一個元素在字符串中的索引爲:index + 2(numRows - 1),即重複週期爲2(numRows - 1)。
除了第一行和最後一行之外,其餘行都還多了一個元素,其下標爲:index + 2(numRows - index - i)
下面是python的實現代碼:
#! /usr/bin/env python
# -*- coding:gbk -*-
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
s_list = []
if numRows == 1 or len(s) == 0:
return s
for i in range(0, numRows):
for index in range(i, len(s), 2*(numRows - 1)):
s_list.append(s[index])
if i != 0 and i != numRows - 1:
if index + 2*(numRows - i - 1) < len(s):
s_list.append(s[index + 2*(numRows - i - 1)])
ret_str = ''.join(s_list)
return ret_str
if __name__ == "__main__":
s = Solution()
print s.convert("PAYPALISHIRING", 3)
#print s.convert("", 3)
#print s.convert("PAYPALISHIRING", 1)