[LeetCode 程序員內功修煉系列] 6. ZigZag Conversion 題解

問題描述

字符串 "PAYPALISHIRING" 寫成指定行數的 zigzag 模式以下,它很像一個字符串在走 Z 字形:python

P   A   H   N
A P L S I I G
Y   I   R
複製代碼

將其每行字符串再連起來:"PAHNAPLSIIGYIR"bash

實現函數,輸入一個字符串和一個行號,返回上述轉換後的字符串app

string convert(string s, int numRows);
複製代碼

例 1:函數

輸入: s = "PAYPALISHIRING", numRows = 3
輸出: "PAHNAPLSIIGYIR"
複製代碼

例 2:spa

輸入: s = "PAYPALISHIRING", numRows = 4
輸出: "PINALSIGYAHRPI"
解釋:

P     I    N
A   L S  I G
Y A   H R
P     I
複製代碼

問題難度

Mediumcode

解題思路

這道題雖然是中等難度,但實際上解起來很簡單,按題目要求,須要把原字符串按必定規則拆成 n 個子字符串,再將這 n 個子字符串首尾相連便可。leetcode

接下來就是如何拆原字符串的問題了,直接看上面的例子也許更容易些字符串

原字符串: PAYPALISHIRING
行數: 4
拆分結果: 
[0]: P     I    N
[1]: A   L S  I G
[2]: Y A   H R
[3]: P     I
複製代碼

上面的 4 個子字符串分別用序號 0-4 表示,接下來咱們再把該序號標記到到原字符串中,每一個字符對應一個序號get

PAYPALISHIRING
01232101232101
複製代碼

發現規律了吧,因而咱們能夠寫一個程序,爲原字符串中的每一個字符標記其所屬的子字符串的序號,而後再根據該序號來構建 n 個子字符串,最後將它們按照升序的順序首位相連。string

這樣作的時間複雜度和空間複雜度都是 O(n),代碼以下:

def convert(self, s, numRows):
    """ :type s: str :type numRows: int :rtype: str """
    index = 0
    sign = 1
    zigzag_array = []
    for c in s:
        if index == 0:
            sign = 1
        elif index == numRows - 1:
            sign = -1
        if len(zigzag_array) < index + 1:
            zigzag_array.append("")

        zigzag_array[index] += c
        index += sign
    return "".join(zigzag_array)
複製代碼

原題連接

相關文章
相關標籤/搜索