[Leetcode] ZigZag Conversion @Python

来源:互联网 发布:心知api怎么呐数据 编辑:程序博客网 时间:2024/05/16 12:20

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)

P   A   H   NA P L S I I GY   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 text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.

我的思路:
字符间的间隔是有规律可循的
第一行和最后一行的间隔为(nRows-1)*2
对于中间行的间距,第i行的间距有两种情况 分别为(nRows-1)*2-(i-1)*2和(i-1)*2

class Solution(object):    def convert(self, s, numRows):        """        :type s: str        :type numRows: int        :rtype: str        """        length = len(s)        out=[]        dis = (numRows-1)<<1        if dis==0:            return s        for i in range(1,numRows+1):            pi = i-1            temp=(i-1)*2            ini = dis - temp            while pi<length:                out.append(s[pi])                if ini == 0: ini = dis                pi = pi + ini                ini = dis - ini        return ''.join(out)
0 0
原创粉丝点击