题目
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)
Example
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P | I | N | ||||
---|---|---|---|---|---|---|
A | L | S | I | G | ||
Y | A | H | R | |||
P | I |
分析
题目的输入为:字符串
s
s
, 划分成的行数
输出为:ZigZag转换后的字符串
分析转换的结果可以发现,ZigZag转换之后的字符串分为 n n 行,其中每个字符进行一个循环,每个字符串的位置与其在原始字符串中的位置有关。
解答
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
rowStr = {k: '' for k in range(numRows)}
period = 2 * numRows - 2
if period == 0:
return s
for i, v in enumerate(s):
idx = i % period
if idx < numRows:
rowStr[idx] += v
else:
rowStr[period-idx] += v
result = ''
for k in range(numRows):
result += rowStr[k]
return result
对于 n=1 n = 1 时,直接返回原字符串 s s <script type="math/tex" id="MathJax-Element-213">s</script>即可。