LeetCode-6 - 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)

image.png

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"

Solution

class Solution(object):
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if len(s) <= numRows or numRows == 1:
            return s
        l = [''] * numRows
        index = 0
        step = 1
        for i in s:
            l[index] += i
            if index >= numRows - 1:
                step = -1
            elif index <= 0:
                step = 1
            index += step
        return "".join(l)

思路

  1. 首先,要想到結(jié)果是一個(gè)numRows個(gè)元素的list,然后將list中的每個(gè)元素相加起來顯示即可
  2. 先觀察第一列的值,基本的步驟是在遍歷字符串的過程中,會(huì)將相應(yīng)的字符置放在list中相應(yīng)的位置。list的index有時(shí)候是+1,有時(shí)候是-1,需要有邏輯進(jìn)行控制。

反思

  1. 解題過程中,想到了用遞歸來生成每個(gè)之形結(jié)果,但是遞歸的結(jié)束條件不好找,字符的index跟list的index不好有一個(gè)對(duì)應(yīng)關(guān)系
  2. 遞歸結(jié)果會(huì)將整個(gè)問題變得更加復(fù)雜
  3. 回過頭來看proposal,這種做法簡單、自然
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容