LeetCode 笔记五 锯齿读文

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一列一列的写入,间隔着会有像锯齿一样的列,锯齿列倒过来写入,最后将这个表格按行读字符(因为我不会写动态表格就用表格代替吧…):

PAHN
APLSIIG
YIR

Example

example 1

Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”

example 2

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”

PIN
ALSIG
YAHR
PI

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的时候都会出问题,就一点一点地改吧。
继续加油吧~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值