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)
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
Example 1:
Example 2:
Related Topics: String
基本上這題就是在找規律,有點麻煩的說…
用一個比較好說明的例子,在找規律的時候,我先觀察了直行的部份:
取出各個 row ,直行的部份,會發現它們都是等差數列,其差值可表示為
另外可以發現,除了第一列與最後一列(row = 0 與 n-1)外,其他列在兩個直行之間會在多輸出一個字元,將這個字元與前一個字元合併用 pair 表示,每一個 pair 都是一個等差,其差值可表示為 ,其中 。
此外,需要稍微注意一下corner case,為了簡單起見,我將 numRows 小於等於 1,以及 numRows 大於等於 s 的長度的 case,做了特別判斷,直接將輸入的 s 回傳回去。
本文作者: 辛西亞.Cynthia
本文連結: 辛西亞的技能樹 / hackmd 版本
版權聲明: 部落格中所有文章,均採用 姓名標示-非商業性-相同方式分享 4.0 國際 (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!