[編程練習]ZigZag Conversion <LeetCode-6>

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:

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




題目來自: https://oj.leetcode.com/problems/zigzag-conversion/

這一題的難度標註爲"Easy",不過我覺得這題目非常有趣。

題目要求是把一個字符串按照它的"Z"形式的順序輸出。所謂"Z"形式就是豎直排列,斜向上換行。

比如 HelloWorld 的三層Z形式是這樣:

H    o      l

e  l W  r  d

l      o

要求輸出的是HolelWrdlo.

解決的思路就是逐行計算如果有可以填充(只要沒有超出原始長度)的字符,它在原始的字符串中應該是什麼位置(sindex, sindex),取到該字符並填充到目標list中。

需要注意的是Z形狀的規律,我是把一個豎直加一個斜方向上升作爲一個單元。

class Solution:
    # @return a string
    def convert(self, s, nRows):
        lists = []
        lens = len(s)
        grp = (2 * nRows - 2) if nRows >= 3 else nRows
        
        for iR in range(nRows):
            sindex = iR
            while sindex < lens:
                lists.append(s[sindex])
                if iR > 0 and iR < (nRows - 1):
                    sindex2 = (sindex + grp - 2 * iR)
                    if sindex2  < lens:
                        lists.append(s[sindex2])
                sindex += grp
        return ''.join(lists)

python討厭的一點是字符串是不可寫的,只能先用字符list,最後再把list通過join的形式構造出字符串來。這題用c語言寫可能更簡潔。
''.join(lists)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章