LeetCode 笔记五 2019/09/27
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);
简单点说就是,把字符遍历一遍,按numRows一列一列的写入,间隔着会有像锯齿一样的列,锯齿列倒过来写入,最后将这个表格按行读字符(因为我不会写动态表格就用表格代替吧…):
P | A | H | N | |||
---|---|---|---|---|---|---|
A | P | L | S | I | I | G |
Y | I | R |
Example
example 1
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
example 2
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
P | I | N | ||
---|---|---|---|---|
A | L | S | I | G |
Y | A | H | R | |
P | I |
Code
渣渣依旧Python3写代码。今天懒得贴写错的代码了,直接贴最后成功的代码:
import numpy as np
class Solution:
def convert(self, s: str, numRows: int) -> str:
r = ''
n = len(s)
i = 0
count = 0
try:
numCols = n//(numRows - 2) +1
except:
numCols = 0
if numCols <= 0:
numCols = n
temp = np.zeros((numRows, numCols), dtype = str)
while n > 0:
if i % 2 == 0:
for j in range(numRows):
if count >= len(s):
break
temp[j][i] = s[count]
count += 1
n -= 1
else:
ntemp = numRows-2
if ntemp <= 0:
ntemp = numRows
for j in range(ntemp):
if count >= len(s):
break
try:
ncol = numRows-(j+2)
except:
ncol = 0
temp[ncol][i] = s[count]
count += 1
n -= 1
i += 1
for t in range(numRows):
l = (temp[t, :]).tolist()
l = ''.join(l)
r = r+l
return r
结果:
1158 / 1158 test cases passed.
Runtime: 244 ms
Memory Usage: 28 MB
Runtime: 244 ms, faster than 8.34% of Python3 online submissions for ZigZag Conversion.
Memory Usage: 28 MB, less than 5.71% of Python3 online submissions for ZigZag Conversion.
写的过程中,遇到了各种问题,比如当numRows = 1
的时候会出一些问题,numRows <= 2
的时候都会出问题,就一点一点地改吧。
继续加油吧~