Leetcode 6. ZigZag Conversion The Solution of Python

来源:互联网 发布:淘宝店铺主页 编辑:程序博客网 时间:2024/06/05 23:24

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

python:

class Solution(object):    def convert(self, s, numRows):        """        :type s: str        :type numRows: int        :rtype: str        """        if numRows==1 or numRows>=len(s):#判断numRows是否为1或超出字符串长度            return s                   res=['']*numRows#创建一个具有numRows个字符串的列表        index,step,R=0,1,""#定义list索引号和遍历需要的方向        for n in s:#遍历s中元素            res[index]+=n #将n存入到当前索引字符串            if index==0:#判断是否到上边界                step=1            elif index==numRows-1:#判断是否到下边界                step=-1            index+=step#如果没有到边界,则按上一次的方向前进一步        R=R.join(res)        return R

以1为步长依次走遍所有字符的思路,还有一种是以每两列为一组,因为没两列是一个轮回,因此判断每一组的方向,加入到字符串中可得结果。

0 0