leetcode ZigZag Conversion 解题报告

 题目地址:

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 agoAccepted76 ms13.4 MBpython3

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值