這是一道找規律的題目

下圖是一個長度為23的字串,在行數為5的情況下其元素對應的情況

我們將其按規律分割成三部分,相鄰部分之間同一位置的元素相差的step = numRows + (numRows - 1)
針對其中一個部分繼續分割,可以發現第一行和最後一行都是隻有一個元素;而中間有一行中有兩個元素

對上圖繼續進行分析可以發現非首尾行元素的第二個元素是(7)等於下一個部分首元素(8)減去非首尾行第一個元素所在行數(1)
於是就可以根據這個規律進行程式碼的編寫了,總體的圖片如下

var convert = function (s, numRows) {
if (numRows == 1) {
return s;
}
var len = s.length + numRows-1;
var step = numRows + (numRows - 2);
var i,j, result = "";
for(i=0; i<numRows; i++){
if(i>0 && i<numRows-1){
let dis = numRows - i-1;
for (j = numRows - 1; j < len; j += step) {
result += s[j-dis] ? s[j - dis] : "";
result += s[j+dis]?s[j+dis]: "";
}
}else if(i == 0 || i == numRows-1){
j=i;
while(j<len - numRows + 1){
result += s[j];
j+=step;
}
}
}
return result;
};
複製程式碼
var convert = function (s, numRows) {
if (numRows == 1) {
return s;
}
var len = s.length;
var step = numRows + (numRows - 2);
var i,j, result = "";
for(i=0; i<numRows; i++){
if(i>0 && i<numRows-1){
for (j=0; j+i < len; j += step) {
result += s[j + i];
if(j+step-i < len){
result += s[j + step - i];
}
}
}else if(i == 0 || i == numRows-1){
j=i;
while(j<len){
result += s[j];
j+=step;
}
}
}
return result;
};
複製程式碼
參考連結: juejin.im/post/5c3a14…