【Description】
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 s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
【Idea】
- 定義numRows長的list溅呢, 每個(gè)元素為 ‘’ 空字符串火邓,對(duì)應(yīng)題干中的每列晒旅,用于存儲(chǔ)遍歷時(shí)對(duì)應(yīng)的字符;
- 對(duì)于給定string s, 對(duì)其中的字符挨個(gè)遍歷,取他的index進(jìn)行計(jì)算茂腥,映射并加入到對(duì)應(yīng)的列场航;
【核心】從字符串中的index到對(duì)應(yīng)組的映射。
通過example可知削罩,字符循環(huán)中,每2(numRows-1)為一個(gè)循環(huán)费奸,其中又分兩部分:
(1)由 0~(numRows-1)弥激, 直接對(duì) 2(numRows-1)取余即可得對(duì)應(yīng)列的下標(biāo);
(2)由(numRows-1)~ 2(numRows-1)愿阐, 直接取余會(huì)超出列數(shù)組的范圍微服,需要做處理: 2(numRows-1) - (i % (2numRows-2));
以上兩部分可以通過對(duì)字符index和numRows-1 數(shù)值比較大小缨历,作為條件以蕴; - ‘’.join(chars)
【Solution】
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows <= 1 or numRows >= len(s):
return s
length = len(s)
chars = ['' for i in range(numRows)]
for i in range(length):
if i % (2*numRows-2) < numRows-1:
index = i % (2*numRows-2)
chars[index] += s[i]
else:
index = (2*numRows-2) - (i % (2*numRows-2))
chars[index] += s[i]
res = ''
return ''.join(chars)