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".
题意:
给一个字符串和一个数字n
将此字符串按着 Zigzag即循环对角线结构 的方式重拍成n行
将重拍后的字符按着横向读取,返回新的字符串
Zigzag即循环对角线结构
参考
http://www.cnblogs.com/zuoyuan/p/3777745.html?utm_source=tuicool
思路:
没有想到建数组,没想到拼接,而要一次性读出来 需要用数学的方式把角标的规律总结出来 需要遍历nRow次,找到符合条件的角标 除去端点还有特殊情况,参差不齐 | 建一个字符串数组tmp,长度为nRow tmp的每个元素内用来记录相应行的字符 然后将tmp的nRow个元素join在一起 就得到按行读取的新string |
通过 index 去指向 tmp 的位置
通过 step 去控制 index 指向位置的规律
通过 i 去读 s 的元素
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows==1: #端点情况
return s
tmp=['' for i in range(numRows)] #字符串数组
index=-1 #通过 index 去指向 tmp 的位置
step=1 #通过 step 去控制 index 指向位置的规律
for i in range(len(s)): #通过 i 去读 s 的元素
index+=step #前走一步,直到numRows换行
if index==numRows:
index-=2 #换行到达的位置
step=-1 #换行后后走一步
elif index==-1: #换到头后,变成tmp1,方向前走
index=1
step=1
tmp[index]+=s[i]
return ''.join(tmp)