蜗牛慢慢爬 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 RAnd then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
翻譯
此題坑爹在于關于zigzag的形式沒有說清楚 然后在leetcode上負分較多
其實只要理解了zigzag的形式就好了
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]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于屏幕分辨率的一些操作
- 下一篇: 字符串编码与转码