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

思路:

Zigzag:即循环对角线结构(

0       8       16      
1     7 9     15 17      
2   6   10   14   18      
3 5     11 13     19      
4       12       20      

向下循环:nRows

斜角线循环:nRows-2(减去首尾两个端点)

重复

参考网页:http://www.cnblogs.com/sanghai/p/3632528.html

 1 /**
 2  * @param {string} s
 3  * @param {number} numRows
 4  * @return {string}
 5  */
 6 var convert = function(s, numRows) {
 7     if(s.length<=numRows||numRows<=1)
 8     {
 9         return s;
10     }
11     var str="";
12     var m=new Array(numRows);
13     var i=0,j;
14     while(i<s.length)
15     {
16         for(j=0;j<numRows&&i<s.length;j++)
17         {
18             if(m[j])
19             {
20                 m[j]+=s[i++];
21             }
22             else
23             {
24                 m[j]="";
25                 m[j]+=s[i++];
26             }
27         }
28         for(j=numRows-2;i<s.length&&j>=1;j--)
29         {
30             if(m[j])
31             {
32                 m[j]+=s[i++];
33             }
34             else
35             {
36                 m[j]="";
37                 m[j]+=s[i++];
38             }
39         }
40     }
41     for(i=0;i<numRows;i++)
42     {
43         str+=m[i];
44     }
45     return str;
46 };

注意:

1.使用var m=[numRows]定义数组的时候,其实定义的是一个含有一个元素numRows的数组m,如果要定义包含numRows个元素的数组,需要使用new Array(numRows);

2.在定义了数组的时候,但是没有赋值的时候,他的值是undefined,比如上述m[0],m[1]...都等于undefined。将他与其他值相加时必须判断,他现在是否有值。

原文地址:https://www.cnblogs.com/baiyuhong/p/5398868.html