日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]

發布時間:2025/3/15 编程问答 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium] 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P A H N A P L S I I G Y I R

And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

翻譯

此題坑爹在于關于zigzag的形式沒有說清楚 然后在leetcode上負分較多
其實只要理解了zigzag的形式就好了

/*n=numRows Δ=2n-2 1 2n-1 4n-3 Δ= 2 2n-2 2n 4n-4 4n-2 Δ= 3 2n-3 2n+1 4n-5 . Δ= . . . . . Δ= . n+2 . 3n . Δ= n-1 n+1 3n-3 3n-1 5n-5 Δ=2n-2 n 3n-2 5n-4 */

Hints

Related Topics: String
一開始我的想法是用二維數組在遍歷的時候把字符存到對應的位置 之后再join到一個字符串里面 這樣挺直觀的 但是python的話慢了一點
事實上我的代碼有點硬推出每個字符的位置填上去的意思(囧) discuss中類似狀態機改變index變化步長的方法顯然更好

代碼

Java

public String convert(String s, int nRows) {char[] c = s.toCharArray();int len = c.length;StringBuffer[] ss = new StringBuffer[nRows];for (int i = 0; i < ss.length; i++) ss[i] = new StringBuffer();int i = 0;while (i < len) {for (int idx = 0; idx < nRows && i < len; idx++)ss[idx].append(c[i++]);for (int idx = nRows-2; idx >= 1 && i < len; idx--)ss[idx].append(c[i++]);}for (int idx = 1; idx < ss.length; idx++)ss[0].append(ss[idx]);return ss[0].toString(); }

Python

class Solution(object):def convert(self, s, numRows):""":type s: str:type numRows: int:rtype: str"""l = len(s)if l<=1 or numRows<=1: return sk = numRows - 2n = l/(numRows+k)+1n = n*(k+1)zigzag = [['']*n for i in range(numRows)]for i in range(l):c = (2*numRows-2)*(i/(2*numRows-2))if (i-c)/numRows==0:zigzag[((i-c)%numRows)][(i/(2*numRows-2))*(k+1)] = s[i]else:zigzag[numRows-2-(i-c)%numRows][(i/(2*numRows-2))*(k+1)+((i-c)%numRows+1)] = s[i]ss =''for i in range(numRows):ss += ''.join(zigzag[i])return ss#better solution class Solution(object):def convert(self, s, numRows):if numRows==1or numRows>=len(s):return sL = ['']*numRowsindex, step = 0, 1for i in s:L[index] += iif index==0:step = 1elif index==numRows-1:step = -1index += stepreturn ''.join(L)

轉載于:https://www.cnblogs.com/cookielbsc/p/7476102.html

總結

以上是生活随笔為你收集整理的蜗牛慢慢爬 LeetCode 6. ZigZag Conversion [Difficulty: Medium]的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。