LeetCode #6 – ZigZag Conversion [字符串]

LeetCode题目链接

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)
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

题意:给定一个字符串,按照“之”字形重排列为n行,输出排列后的字符串。注意当n=1时,重排后的结果还是原字符串。用一个方向dir记录之字形的走向,遍历字符串重排即可。

class Solution:
    def convert(self, s, numRows):
        if numRows == 1: return s
        v = ['' for i in range(numRows)]
        cur, dir, res = 0, -1, ''
        for c in s:
            if cur == 0 or cur == numRows - 1:
                dir = -dir
            v[cur] += c
            cur += dir
        for i in v: res += i
        return res

欢迎留言