LeetCode6-Z字型變換
阿新 • • 發佈:2018-11-19
昨天和她的父親聊天的時候,他直接問我:你最近同我女兒聯絡否?這著實是把我弄得一愣一愣的,哈哈哈哈,到今天想想也是蠻有趣的。
這一題官方給的解題方法是按行排序和按行訪問兩種方法,好肯定是很好的,但我還是想先把我第一次的方法給貼出來,因為我覺得這個可能對我們這些菜鳥會更容易接受些(大神繞道)
方法一:得出Z字型矩陣
這個方法就很直接了,題目不是要我們求出一個字串Z字型變換嘛,那我們就先把它的Z字型矩陣求出來,再依次按行讀取相應元素即可得出最終答案,是不是很簡單。
程式碼如下:
class Solution: def convert(self, s, numRows): if numRows <= 1: return s DecArray = self.getArray(s, numRows) result = ''.join(DecArray.flatten()) result = result.replace('-', '') return result # 構建Z型陣列法獲得相關陣列 def getArray(self, s, numRows): DecArray = np.array([['-'] * len(s)] * numRows) ArrayIndex = 0 IndexCol = 0 while ArrayIndex < len(s): if IndexCol % (numRows - 1) == 0: line = ArrayIndex - (2 * numRows - 2) * int(IndexCol / (numRows - 1)) if line < numRows: DecArray[line][IndexCol] = s[ArrayIndex] else: IndexCol += 1 ArrayIndex -= 1 else: sum = int(IndexCol / (numRows - 1) + 1) * (numRows - 1) line = sum - IndexCol DecArray[line][IndexCol] = s[ArrayIndex] IndexCol += 1 ArrayIndex += 1 return DecArray
但是這個最簡單的方法的執行效率也真是不咋地,硬是沒跑出來,報了超出時間限制的錯誤。當時確實是對我有些打擊,覺得沒有哪塊地方要花費很長時間,想來想去最後用了官方給的方法才得出答案,還是有些不爽的。
方法二:按行排序法
思路
通過從左向右迭代字串,我們可以輕鬆地確定字元位於 Z 字形圖案中的哪一行。
演算法
我們可以使用 \text{min}( \text{numRows}, \text{len}(s))min(numRows,len(s)) 個列表來表示 Z 字形圖案中的非空行。
從左到右迭代 ss,將每個字元新增到合適的行。可以使用當前行和當前方向這兩個變數對合適的行進行跟蹤。
只有當我們向上移動到最上面的行或向下移動到最下面的行時,當前方向才會發生改變。
程式碼如下:
class Solution: def convert(self, s, numRows): if numRows <= 1: return s DecDict = self.getArray(s, numRows) rows = min(len(s), numRows) ListStr = [] for line in range(rows): ListStr.extend(DecDict[line]) return ''.join(ListStr) # 按行排序法獲得相關陣列 def getArray(self, s, numRows): rows = min(len(s), numRows) DecDict = {} for row in range(rows): DecDict[row] = [] curRow = 0 goingDown = False for index in range(len(s)): DecDict[curRow].extend(s[index]) if curRow == 0 or curRow == numRows - 1: goingDown = not goingDown curRow += 1 if goingDown else -1 return DecDict
這個方法是真的香啊!!!哈哈哈哈,真的受啟發了,但執行效率也是慘不忍睹,不過能通過就行了。