leetcode_6. ZigZag Conversion 按行打印ZigZag 后的结果

来源:互联网 发布:网络修复dns配置 编辑:程序博客网 时间:2024/05/16 07:23

题目:

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".


题意:

字符串s按照ZigZag 样式排列后,按行打印排列后的结果


代码:

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        
        n = len(s)
        
        if n <= numRows or numRows <= 1 :    #特殊情况,尤其是numRows=1的情况要考虑
            return s
        else :
            res = ''      #记录结果
            
            size = 2*numRows - 2    #每一组的元素个数
            
            group = n/size + 1    #s中元素一共有多少组
            
            for i in range(numRows) :#遍历每一行
                 for j in range(group) :    #遍历每一组
                     pos1 = i + j*size    #第i行的每一组的第一个元素(竖着的元素),pos1为元素在s中的下标
                     if pos1 < n :
                         res += s[pos1]       #将该组第一个元素加入结果中
                     if i != 0 and i != numRows-1 and pos1 < n :   #如果该行不是第一行和最后一行,且pos1位置在n以内,则每一组还有第二个元素(斜着的元素),开始计算第j组的第二个元素在s中的下标pos2
                         pos2 = j*size + size-i   #第j组的起始位置为j*size,第二个元素的偏移为size-i,这是关键点
                         if pos2 < n :
                             res += s[pos2]       #将该组第二个元素加入结果中
            
            return res
            

笔记:

首先要对Zigzag结构要有所了解。长度为n的字符串,按numRows行来排列Zigzag,可以将一竖和一斜两列看成一组,则一组包含的元素个数为size = 2*numRows - 2,长度为n的字符串一共有group = n/size + 1组。

按行打印时,先遍历每一行i,然后在每一行遍历每一组j,得到每组的第一个元素位置pos1后,如果该组还有第二个元素,则根据该组第二个元素的偏移,计算第二个元素的位置pos2。

Zigzag:即循环对角线结构(

0   8   16   1  79  1517   2 6 10 14 18   35  1113  19   4   12   20   
                



0 0
原创粉丝点击