==============================================================================
【id】#6
【title】 ZigZag Conversion
【description】
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
【idea】
ZigZag也就是把字符串转换成指定行数的“Z”字形,然后按照每一行从左往右读出来。
参考看一些资料才知道规律。
【code】
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 : return s
res = ''
length = len(s)
for i in range(numRows):
step1 = 2*(numRows - i -1)
step2 = 2*i
pos = i # 定义字符串中的下标
if pos <length: res += s[pos]
else: break
while True:
pos += step1
if pos >=length: break
res += s[pos] if step1 else ''
pos += step2
if pos >= length: break
res += s[pos] if step2 else ''
return res
【idea2】
借助数组存储zigzag后的字符串,字符串按照位置写入数中的每一行。如果是在数组的第一行,那么接下来依次读取的字符都要依次加一行直到最后一行;到了最后一行之后,每次读取的字符都要写入上一行,也就是每次减一行。
【code】
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1: return s
row = 0
step =1
res = [''] *len(s)
for x in s:
if row ==0: step = 1
if row == numRows -1: step = -1
res[row] += x
row += step
return ''.join(res)
==============================================================================