https://leetcode.com/problems/zigzag-conversion/submissions/
Success
Runtime: 44 ms, faster than 92.48% of Python online submissions forZigZag Conversion.
Memory Usage: 11.9 MB, less than 24.97% of Python online submissions for ZigZag Conversion.
思路:
找规律,多举几个例子,发现下标规律
当numRows = 3 , 第一行下标都是4, (mod = 4)的倍数,余数为0;
第二行, 下标 % mod , 得到余数为 1, mod-1 ;
第三行, 下标 % mod , 得到余数为 2;
当numRows = 4 , 第一行下标都是6,(mod = 6)的倍数, 余数为0;
第二行, 下标 % mod , 得到余数为 1, mod-1 ;
第三行, 下标 % mod , 得到余数为 2 , mod -2;
第四行, 下标 % mod , 得到余数为 3;
当numRows =5 , 第一行下标都是8,(mod = 8)的倍数, 余数为0;
当numRows =K , 第一行下标都是(K-1)*2,(mod = (numRows-1)*2)的倍数, 余数为0;
第二行, 下标 % mod , 得到余数为 1, mod-1 ;
第三行, 下标 % mod , 得到余数为 2 , mod -2;
第四行, 下标 % mod , 得到余数为 3, mod -3
。
。
。
第K行, 下标 % mod , 得到余数为K-1
代码实现:
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
slen = len(s)
res = ''
mod = (numRows-1)*2
i = 0
for i in range(numRows):
k = i
while True:
if k>= slen :
break
res+= s[k]
if i >0 and (i< numRows-1):
if k-i+mod-i>=slen:
break
res+= s[k-i+mod-i]
k+= mod
return res
'''
s= Solution()
print s.convert("PAYPALISHIRING", 3)
print s.convert("PAYPALISHIRING", 4)
print s.convert("a", 2)
'''
class Solution(object):
def convert(self, s, numRows):
leng = len(s)
if leng == 0: return ''
if numRows <= 0: return ''
elif numRows == 1: return s
resRows = [''] * numRows
i = 0
resRowNum = 0
step = 1
while i < leng:
resRows[resRowNum] += s[i]
if ( resRowNum == numRows - 1) :
step = -1
elif ( resRowNum == 0):
step = 1
resRowNum += step
i += 1
return ''.join(resRows)
6. ZigZag Conversion
Medium
10513268FavoriteShare
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:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Accepted