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)
就是按锯齿状排列一个字符串,然后按行输出排列后的结果。
一开始还想了一个很搓的 O ( n 2 ) O(n^2) O(n2)的方法,就是先按要求把字符串保存到到一个二维数组中,再按行打印。
然后看了答案,直接O(n),按顺序输出即可。
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
initRows = min(numRows,len(s))
rows = [""]*initRows
print(rows)
dowFlag = False # 用来控制遍历方向是上还是下
curRow = 0
for c in s:
print(curRow)
rows[curRow]+=c
if ((curRow == 0) or (curRow == numRows - 1)):
dowFlag = ~dowFlag # 按位取反运算符~
if dowFlag:
curRow += 1
else :
curRow += -1
ans = ""
for row in rows:
ans += row
return ans
rows 就是用来保存每行的结果,dowFlag 用来控制向上或者向下,始终在0和numRows 之间摆动。如果dowFlag 为 True,表示向下移动,curRow 每次加1;如果dowFlag 为 False,表示向上移动,curRow 每次减1。这样每次向rows中的一行插入一个字符。遍历完s字符串之后,再拼接rows的每一行,即可得到最终结果。
THE END.
博客围绕LeetCode锯齿字符串排列问题展开,先介绍最初想到的O(n2)方法,即把字符串存到二维数组再按行打印,后看到答案可直接O(n)按顺序输出。还给出Python代码实现,通过控制方向标志和行索引,遍历字符串后拼接每行结果。
863

被折叠的 条评论
为什么被折叠?



