【leetcode】ZigZag Conversion

題目簡述

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 N
A P L S I I G
Y 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:app

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".this

解題思路:

這個題目有兩種作法:第一種是模擬,也就是說咱們能夠有幾行就開幾個數組都存起來,最後合到一塊兒就能夠了;另外一種方法是找規律。由於第一種比較直觀,故代碼實現了第一種思路:code

class Solution:
    # @return a string
    def convert(self, s, nRows):
        if nRows == 1:
            return s
        gap = nRows - 2
        res = []
        for i in range(nRows):
            res.append([])
        i = 0
        while i < len(s):
            for j in range(nRows):
                if i >= len(s):
                    break
                res[j] += s[i]
                i += 1
            for j in range(gap,0,-1):
                if i >= len(s):
                    break
                res[j] += s[i]
                i += 1
        ress = ""
        for i in res:
            for j in i:
                ress += j
        return ress
相關文章
相關標籤/搜索