ZigZag Conversion:是指定一个长度,将一个序列的字符依次放到长度对应的正方形的竖边和对角线上。比如:
有01234567891234567 ,对应的长度为4的矩阵列则是
0 6 3
1 5 7 2 4
2 4 8 1 5 7
3 9 6 最终得到的序列则是 063 15724 248157 396
具体的算法是 定义一个长度为4的列表,将 前4个字符放到对应的位置中,第五个字符则跟倒数第二个字符合并放到列表的倒数第二个位置,第6个依次类推,当字符跟列表第一个合并后,则顺序往下合并。
具体代码如下:
def convert(s, numRows):
if numRows == 1 or numRows >= len(s):
return s
L = [''] * numRows
index, step = 0, 1
for x in s:
L[index] += x
if index == 0:
step = 1
elif index == numRows -1:
#顺序往列表插入n个字符后,n+1则倒序合并(即往后退一步)
step = -1
index += step
return L
还有一种是在博客看到用多重循环来做(分竖列和对角线不同情况赋值)
首先先给竖列赋值n个字符,然后再给对角线赋值 n-2个字符(剔除对角线的俩个)
string convert(string s,
int
nRows){
if
(nRows == 1)
return
s;
string res[nRows];
int
i = 0, j, gap = nRows-2;
while
(i < s.size()){
for
(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];
for
(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++];
}
string str =
""
;
for
(i = 0; i < nRows; ++i)
str += res[i];
return
str;
}