0
点赞
收藏
分享

微信扫一扫

模拟卷Leetcode【普通】006. Z 字形变换

小月亮06 2022-03-12 阅读 69

汇总:模拟卷Leetcode 题解汇总

006. Z 字形变换

将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:

P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“PAHNAPLSIIGYIR”。

请你实现这个将字符串进行指定行数变换的函数:

string convert(string s, int numRows);

示例 1:

输入:s = “PAYPALISHIRING”, numRows = 3
输出:“PAHNAPLSIIGYIR”
示例 2:
输入:s = “PAYPALISHIRING”, numRows = 4
输出:“PINALSIGYAHRPI”
解释:
P I N
A L S I G
Y A H R
P I
示例 3:

输入:s = “A”, numRows = 1
输出:“A”

提示:

1 <= s.length <= 1000
s 由英文字母(小写和大写)、’,’ 和 ‘.’ 组成
1 <= numRows <= 1000

代码:

from leetcode_python.utils import *


class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if 1==numRows:return s
        lines = ['']*numRows
        rowid,dir = 0,1
        for i,c in enumerate(s):
            lines[rowid]+=c
            rowid+=dir
            if 0==rowid:dir=1
            elif numRows-1==rowid:dir=-1
        print(lines)
        return ''.join(lines)


def test(data_test):
    s = Solution()
    data = data_test  # normal
    # data = [list2node(data_test[0])]  # list转node
    return s.convert(*data)


def test_obj(data_test):
    result = [None]
    obj = Solution(*data_test[1][0])
    for fun, data in zip(data_test[0][1::], data_test[1][1::]):
        if data:
            res = obj.__getattribute__(fun)(*data)
        else:
            res = obj.__getattribute__(fun)()
        result.append(res)
    return result


if __name__ == '__main__':
    datas = [
        ["AB",1],
    ]
    for data_test in datas:
        t0 = time.time()
        print('-' * 50)
        print('input:', data_test)
        print('output:', test(data_test))
        print(f'use time:{time.time() - t0}s')

备注:
GitHub:https://github.com/monijuan/leetcode_python

CSDN汇总:模拟卷Leetcode 题解汇总

可以加QQ群交流:1092754609

举报

相关推荐

0 条评论