6. ZigZag Conversion

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".

 1 /**
 2  * @param {string} s
 3  * @param {number} numRows
 4  * @return {string}
 5  */
 6 var convert = function(s, numRows) {
 7     var resArr = [];
 8     var len = s.length;
 9     
10     var index = 1;
11     
12     //1行的或者直接就是空的,直接就输出了
13     if(numRows === 1 || !s){
14         return s;
15     }
16     
17     //初始化
18     for(var i = 0;i < numRows;i++){
19         resArr[i] = '';
20     }
21     
22     //一直上下循环添加
23     for(var i = 0;i<len;i++){
24         
25         if(index == 1){
26             
27              sub = 1;
28         }
29         
30         if(index == numRows){
31             sub = -1;
32         }
33         
34         resArr[index - 1] += s[i];
35         index += sub;
36         
37     }
38     
39     return resArr.join("");
40     
41 };

 

posted @ 2017-10-08 21:55  hdu胡恩超  阅读(118)  评论(0编辑  收藏  举报