题目地址:
https://leetcode.com/problems/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:
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
N型字符串转换,然后按照行输出
转换后的字符串共n行,对图形进行划分,每一列至下一列为一块,如Example 2 中PAYPAL为第一个块,每一块的大小为:size=n*2-2,最后一块的大小可能会小于这个size的值。
将转换后的字符串分成三部分处理:
第1行,第2行至n-1行,第n行。
第1行
i=0:从第0块到k-1块依次循环,选中的字符为:k*size。
k=0时,如Example 2 中第1行的P
第2行至n-1行
i in [1,.....n-2]
i代表行号,从第0块到k-1块依次循环,每次选中两个字符,分别为size*k-i,size*k+i,
同时需要对size*k-i 和size*k+i做越界判定,第一块没有前一个字符,最后一个块可能因为字符不够而没有后一个字符或两个都没有。
i=1,k=0时,如Example 2 中第2行的A
i=1,k=1时,如Example 2 中第 3 行的L、S
第n行
i=n-2
最后一行,从第0块到k-1块依次循环,选中的字符为:k*size+i
k=0时,如Example 2 中第4行的P
边界问题:
当n为1时或大于字符串长度时,应把字符串直接输出。
python3实现代码:
class Solution:
def convert(self, s: str, numRows: int) -> str:
size=numRows*2-2
str_size=len(s)
if numRows == 1 or numRows >= str_size:
return s
max_k=int(str_size/size)+2
re=""
#print(size,str_size,max_k)
#i=0
for k in range(max_k):
if k*size < str_size:
re+=s[k*size]
#print(re)
#i in 1 ~ numRows-2
if numRows > 2:
for i in range(1,numRows-1):
for k in range(max_k):
if 0 < k*size-i < str_size:
re+=s[k*size-i]
if 0 < k*size+i < str_size:
re+=s[k*size+i]
#print(re)
# i=numRows
i=numRows-1
for k in range(max_k):
if k*size+i<str_size:
re+=s[k*size+i]
#print(re)
return re
运行结果:
Time Submitted | Status | Runtime | Memory | Language |
---|---|---|---|---|
4 minutes ago | Accepted | 76 ms | 13.4 MB | python3 |