Skip to content

Latest commit

 

History

History
76 lines (58 loc) · 1.92 KB

6 Z字形变换.md

File metadata and controls

76 lines (58 loc) · 1.92 KB

6 Z字形变换

一、题目

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

image

比如输入字符串为"LEETCODEISHIRING"行数为3时,排列如下:

L   C   I   R
E T O E S I I G
E   D   H   N

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。

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

string convert(string s, int numRows);
  • 示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
  • 示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:

L     D     R
E   O E   I I
E C   I H   N
T     S     G

二、Python3程序

image

# -*- coding:utf-8 -*-
# &Author  AnFany

# 6_ZigZag_Conversion  Z字形变换


class Solution:
    def convert(self, s: str, numRows: int) -> str:
        # 行数等于1,原样返回,等于0,返回空字符串
        if numRows == 1:
            return s
        elif not numRows:
            return ''

        # 按照得到的规律进行编程
        trans_str = ''
        # 字符串长度
        length = len(s)

        for i in range(numRows):
            start_index = i
            index_gap = [2 * (numRows - 1) - 2 * i, 2 * i]
            gap = 0  # 控制选取间隔的索引
            while start_index < length:
                if index_gap[gap]:  # 对于前一个间隔为0的,需要判断,不能添加同一个字符。
                    trans_str += s[start_index]
                start_index += index_gap[gap]
                gap = not gap  # 间隔进行循环
        return trans_str