LeetCode_Everyday:006 ZigZag Conversion

LeetCode_Everyday:006 ZigZag Conversion


LeetCode Everyday:堅持價值投資,做時間的朋友!!!

題目:

將一個給定字符串根據給定的行數,以從上往下、從左往右進行Z字形排列。比如輸入字符串爲"LEETCODEEISHIRING"行數爲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
    

代碼

方法一: 利用字符串行索引的循環關係求解,下面是同一個方法的不同實現方式。題注

執行用時 :88 ms, 在所有 Python3 提交中擊敗了35.36%的用戶
內存消耗 :13.7 MB, 在所有 Python3 提交中擊敗了5.00%的用戶

class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        if numRows < 2: return s
        res = ["" for _ in range(numRows)]
        i, flag = 0, -1
        for c in s:
            res[i] += c
            if i == 0 or i == numRows - 1: flag = -flag
            i += flag
        return "".join(res)      
    
"""
For Example:    input:   s = "LEETCODEISHIRING"  numRows = 3
               output:   "LCIRETOESIIGEDHN"
"""
s = "LEETCODEISHIRING"
numRows = 3
                
solution = Solution()
result = solution.convert(s, numRows)
print('輸出爲:', result)  #  LCIRETOESIIGEDHN


class Solution:
    def convert(self, s, numRows):
        """
        :type s: str
        :type numRows: int
        :rtype: str
        """
        cache = [i for i in range(numRows)] + [i for i in range(1, numRows-1)][::-1]
        res = [""] * numRows
        for i, c in enumerate(s):
            res[cache[i%len(cache)]] += c
        return "".join(res)      
    
"""
For Example:    input:   s = "LEETCODEISHIRING"  numRows = 3
               output:   "LCIRETOESIIGEDHN"
"""
s = "LEETCODEISHIRING"
numRows = 3
                
solution = Solution()
result = solution.convert(s, numRows)
print('輸出爲:', result)  #  LCIRETOESIIGEDHN

圖解:

引用的圖片有利於幫助你找到字符串行索引的循環關係

參考

  1. https://leetcode-cn.com/problems/zigzag-conversion/solution/zzi-xing-bian-huan-by-jyd/
  2. https://www.bilibili.com/video/BV1n7411S7Vo

此外

  • 原創內容轉載請註明出處
  • 請到我的GitHub點點 star
  • 關注我的 CSDN博客
  • 關注公衆號:CV伴讀社

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章