[Leetcode 6] ZigZag Conversion

原题说明

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)

1
2
3
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:

1
2
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

1
2
3
4
5
6
7
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I

解题思路

这道题需要把一个字符串变成ZigZag的排列后按行输出。所以我们只需要依次判断每个字符应该出现在ZigZag排列中的哪一行就可以了。
对于一个N行的ZigZag排列,我们可以把它看作一个周期为2N - 2的循环。在这个周期内,如果一个字符位于周期的前N位,
那么它的位数就是行号。如果在N位置后,那么它的行号就是超出部分的倒序,如N + 1那么,行号就是N - 1. (以上行号,从1开始计)

示例代码 (python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
rows = ['' for i in range(numRows)]
for i in range(len(s)):
r = i % (2 * numRows - 2)
if r >= numRows:
r = 2 * numRows - r - 2
rows[r] += s[i]
return ''.join(rows)

复杂度分析

时间复杂度: O(n) 其中ns的长度
空间复杂度: O(n)

归纳总结

这道题难度不高, 只需要考虑清楚字符串转换前后的对应关系即可。

------ 关注公众号:猩猩的乐园 ------