LeetCode 6. ZigZag Conversion Python3

本文介绍了LeetCode第6题ZigZag Conversion的Python3解决方案。通过创建一个二维数组并按特定逻辑填充,实现了字符串在指定行数下的Z字形排列。此外,还讨论了一种更高效的算法,通过控制变量来确定字符应处于哪一行,以优化性能。
摘要由CSDN通过智能技术生成

LeetCode 6. ZigZag Conversion Python3

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

问题分析

本题是一道中等题,题目的意思是给定一个字符串s和行数numRows,是按从上往下、从左往右的z字型排列的,现在需要你返回按行排列得到的字符串。

题目的意思很简单,在实现的过程中需要注意的就是控制好逻辑,我最开始的想法是设定一个二位数组,按照题目的要求去存储字符串,然后按行去遍历,得到的就是最后的结果,这样做可以满足要求,但就是效率不太高,代码如下:

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if not s:
            return ""
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值