6. Z 字形变换
程序员文章站
2022-04-17 16:41:17
...
思路1:72 ms 13 MB。考虑给字符串进行编号。对于“LEETCODEISHIRING”,当行数为4时,编号为012321,不断重复,最后根据编号(实际是行号)进行稳定排序,最终即答案。
import copy
class Solution():
def convert(self, s , numRows ):
str = [x for x in s]
index1 = [x for x in range(0,numRows)]
index2 = [x for x in range(numRows-2,0,-1)]
index1+=index2
basicindex = copy.copy(index1) # 浅赋值 基本的编号,后续重复
for i in range(len(str)//len(index1)+1):
index1+=basicindex
str = list(zip(index1,str))
newString = sorted(str,key=lambda x:x[0])
finalString = [x[1] for x in newString]
ans = "".join(finalString)
return ans
思路2:56 ms 13.1 MB。上面的排序过程还是比较费时。基于上面的思想,直接在遍历字符串的过程中,在对应的行加上字符即可。
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows < 2: return s
res = ["" for _ in range(numRows)]
i, flag = 0, -1
for c in s:
res[i] += c
if i == 0 or i == numRows - 1: flag = -flag
i += flag
return "".join(res)
上一篇: 视觉惯性里程计 VIO
下一篇: 视觉里程计的入门实践