6. ZigZag Conversion

暴力解法就直接双指针,一个遍历s,一个跟踪row index,生成整个 zigzag 之后join返回。

除了这样维护row index之外,想看看有没有什么循环规律,按照两个example写一下idx, mode, row就看出来了,这方法像做二年级奥数...

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        zigzag = ['' for _ in range(numRows)]
        if numRows == 1 or numRows >= len(s): return s
        
        index, step = 0, 1

        for x in s:
            zigzag[index] += x
            if index == 0: step = 1
            elif index == numRows -1: step = -1
            index += step

        return ''.join(zigzag)

Last updated

Was this helpful?