LeetCode 6. ZigZag Conversion(Python)兼翻译

来源:互联网 发布:300533冰川网络 编辑:程序博客网 时间:2024/06/06 03:56

6. ZigZag Conversion

转化成锯齿形

本题来自LeetCode OJ


题目翻译

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)
给定行数,将字符串"PAYPALISHIRING" 写成锯齿的形式,如下图所示:

P   A   H   NA P L S I I GY   I   R

And then read line by line: "PAHNAPLSIIGYIR"
然后一行一行的读取则为:
"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".

注:ZigZag是锯齿形,也就是每条边是相同的字符个数


题目分析

根据锯齿状的结构,我们以字符串长度为10,ZZ n行为例:
第一行:第一个下标索引为0,下一个为竖下来这笔需要n-1个,斜过去这笔为n-1,所以第二个下标索引为2(n-1).我们很简单就可以看出规律,是(n-1)的倍数。
所以第二行呢?
第二行的情况一共有两种:
- 竖下来的第一行的下一个
- 斜上去第一行的上一个
也就是说是(n-1)整除余1或者余(n-2)
……
所以规律出来了:

if (i % nextnum) == j or (i % nextnum) == nextnum-j:                        ZigZag += s[i]                        dellist.append(i)

但是一个i在某一行就必定不在别的行,所以接下来我们进行删除操作,这样越到后面代码所需要迭代的次数就越少了。


代码示例

class Solution(object):    def convert(self, s, numRows):        """        :type s: str        :type numRows: int        :rtype: str        """        if len(s) <= numRows or numRows == 1:            ZigZag = s        else:            ZigZag = ""            Candidate = [i for i in range(len(s))]            nextnum = 2*(numRows-1)            for j in range(numRows):                dellist = []                for i in Candidate:                    if (i % nextnum) == j or (i % nextnum) == nextnum-j:                        ZigZag += s[i]                        dellist.append(i)                for i in dellist:                    Candidate.remove(i)        return ZigZag

自己心累

最开始写的时候用错了remove,倒是程序总是得不到我想要的答案。不能够直接remove,我猜应该是remove了之后,for i in Candidate中的索引就变了。

0 0
原创粉丝点击