6. ZigZag Conversion
题目:
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);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
代码:
看了半天,都没怎看懂题目。查了一下,原来:
Zigzag:即循环对角线结构(
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 |
)
这样子的话,就不算麻烦了,只要正确的字符串操作,把每个元素加在正确的位置就好。
于是,共有numRows行,所以定义一个保护numRows元素的数组,用来保存每一行的字符串。
观察规律,第一列从0写到numRows-1,之后从后往前,及numRows-2到0开始逐渐添加。输出并不需要考虑宽度,所以对字符串来说,之后往后加就好
//凑了半天,总算凑出来了
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
i = 0
j = 0
gap = numRows-2
temp= ['' for x in range(numRows)]
while i<len(s):
while(j<numRows):
if(i>=len(s)):break
temp[j] += str(s[i])
j += 1
i += 1
j=gap
while(j>0):
if(i>=len(s)):break
temp[j] += str(s[i])
j -= 1
i += 1
result = ''
for y in temp:result += y
return result
//网上查的,好像更直观
def convert2(self, s, nRows):
if nRows==1: return s
tmp=['' for i in range(nRows)]
index=-1; step=1
for i in range(len(s)):
index+=step
if index==nRows:
index-=2; step=-1
elif index==-1:
index=1; step=1
tmp[index]+=str(s[i])
return ''.join(tmp)
测试了多次,两个速度差不多,必定时间复杂度和空间复杂度都一样: