题目要求给定一个字符串,然后将其按顺序以之字排列,然后将字母串按行来输出,其中之子字符回路的行数由参数numRows控制。
比如,
example1:
输入 s= “PAYPALISHIRING”,numRows=3, 输出=”PAHNAPLSIIGYIR”
P A H N
A P L S I I G
Y I Rexample2:
输入 s= “PAYPALISHIRING”,numRows=4, 输出=”PINALSIGYAHRPI”
P I N
A L S I G
Y A H R
P I
这个题目,我先对给出的两个例子进行了分析,首先第一行和最后一行的相邻元素在输入字符串中的位置都差了numRows*2-2,而中间行的字符在输入字符串的位置相差都是有规律的,比如example中的第二行间隔为4,2,4,2,4……,第三行间隔为2,4,2,4……。因此,也就是相邻间隔值相加为numRows*2-2。因此,代码如下所示:
C++:
@by_chandepire
string convert(string s, int numRows)
{
string result = "";
int len = s.size(),k;
if(len <= numRows || numRows == 1) return s;
int temp = (numRows<<1)-2;
for(k=0;k<len;k = k + temp)
result += s[k];
for(int i = 1;i<numRows-1;++i)
{
int j = i<<1;
for(k=i;k<len;k = k + j)
{
result += s[k];
j = temp - j;
}
}
for(k=numRows-1;k<len;k = k + temp)
result += s[k];
return result;
}
python:
@by_chandepire
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
result = ""
length = len(s)
if length <= numRows or numRows == 1:
return s
k = 0
temp = (numRows<<1) - 2
while k < length:
result = result + s[k]
k = k + temp
for i in range(1,numRows-1):
j = (i<<1)
k = i
while k < length:
result = result + s[k]
j = temp - j
k = k + j
k = numRows - 1
while k<length:
result = result + s[k]
k = k + temp
return result