首页 > 编程 > Python > 正文

leetcode zigzag conversion(python)

2019-11-08 01:41:41
字体:
来源:转载
供稿:网友

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

zigzag 是什么意思捏:

row=4     06

  15 7

                  24 8

  39

就是这样子的格式微笑

python 代码:

class Solution(object):    def convert(self, s, numRows):        """        :type s: str        :type numRows: int        :rtype: str        """        l=[]        for i in range(numRows):            l.append("")        num=numRows*2-2                for i,j in enumerate(s):            if num==0:                return s            elif i%num<numRows:                index=i%num                l[index] +=j            else:                index -=1                l[index] += j        return "".join(l)还看到一位大神的代码,比我的高明多了。。。。

比numrow小,index 加一,其他减一


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表